How to convert XML to objects in Swift?

2

How can I convert responses from XML requests to objects in Swift, just like ObjectMapper does with JSON for objects?

    
asked by anonymous 08.07.2016 / 15:19

1 answer

0

You need to implement NSXMLParserDelegate :

Declare two global variables

var xmlParser: NSXMLParser!
var currentContentElement: NSMutableString!

Then in the method that receives the response from the SOAP request you call xmlParser

xmlParser = NSXMLParser(data: responseData)
xmlParser.delegate = self
xmlParser.parse()

Implementation of NSXMLParserDelegate :

func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
    self.currentContentElement = NSMutableString()
}

func parser(parser: NSXMLParser, foundCharacters string: String) {
    self.currentContentElement.appendString(string)
}

func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
    switch elementName {
    case "CAMPOXXXX":
        let variavelxxx = currentContentElement.integerValue
        break
    default:
        break
    }
    self.currentContentElement = nil
}

func parserDidEndDocument(parser: NSXMLParser) {

}

It's very simple in the didEndElement method to get the values you need and play on your object.

I hope I have helped you = D

    
24.05.2017 / 20:20