Using Swift4, iOS11.1, Xcode9.1,
Using the new Swift4 typealiase "Codable" works well for JSON-decoding (as explained here or here or in many other contributions). However, as it comes to XML-parsing, I couldn't find any information on whether this "Codable" protocol could also be used for XML-decoding.
I tried to use the XMLParser (as can be seen in code-excerts below). But I failed to used the "Codable" protocol as to simplify the XML-parsing process. How would I have to use the Codable-protocol exactly to simplify XML-parsing ??
// the Fetching of the XML-data (excert shown here with a simple dataTask) :
let myTask = session.dataTask(with: myRequest) { (data, response, error) in
// check for error
guard error == nil else {
completionHandler(nil, error!)
return
}
// make sure we got data in the response
guard let responseData = data else {
let error = XMLFetchError.objectSerialization(reason: "No data in response")
completionHandler(nil, error)
return
}
// the responseData is XML !!!!!!!!!!!!!!
let parser = XMLParser(data: responseData)
parser.delegate = self
parser.parse()
}
myTask.resume()
The corresponding XMLParserDelegate-methods:
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
self.resultTrip = elementName
// print(elementName)
if (self.resultTrip == "TripResult") {
self.resultTime = ""
}
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
let data = string.trimmingCharacters(in: .whitespacesAndNewlines)
if data.count != 0 {
switch self.resultTrip {
case "TimetabledTime": self.resultTime = data
default: break
}
}
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if self.resultTrip == "TripResult" {
// HERE IS THE MISSING BIT: HOW DO YOU USE A CODABLE struct ???
var myTrip = TripResult(from: <#Decoder#>)
myTrip.resultID = self.resultTrip
}
print(resultTime)
}
The struct :
struct TripResult : Codable {
let resultId : String?
let trip : Trip?
enum CodingKeys: String, CodingKey {
case resultId = "ResultId"
case trip
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
resultId = try values.decodeIfPresent(String.self, forKey: .resultId)
trip = try Trip(from: decoder)
}
}
How would I have to use the 'codable' struct ?? Is there any nice example on how to use the Codable-protocol for XMLparsing ?? Any help appreciated !