How to convert XML to Swift objects?

Asked

Viewed 70 times

2

How can I convert XML request replies to objects in Swift format, just like Objectmapper does with JSON for objects?

  • 1

    Take a look, it might help you https://github.com/drmohundro/SWXMLHash

  • Yes it is managed to use that same, is the best :D. Puts your suggestion as answer and I accept! Hug and Thank you.

1 answer

0

You need to implement the NSXMLParserDelegate:

Declare two global variables

var xmlParser: NSXMLParser!
var currentContentElement: NSMutableString!

Then in the method that receives the answer of the SOAP request you call the 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 method didEndElement you take the values you need and play on your object.

I hope I helped you =D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.