How do I parse XML web service in Swift?
For anyone still looking, here is the code I used that worked quite well to convert the xml response into Dictionaries/Arrays, thanks to the SWXMLHash class...
UPDATED SWIFT 2.0
let baseUrl = "http://www.example.com/file.xml" let request = NSMutableURLRequest(URL: NSURL(string: baseUrl)!) let session = NSURLSession.sharedSession() request.HTTPMethod = "GET" var err: NSError? let task = session.dataTaskWithRequest(request) { (data, response, error) in if data == nil { print("dataTaskWithRequest error: \(error)") return } let xml = SWXMLHash.parse(data) if let definition = xml["entry_list"]["entry"][0]["def"].element?.text { // ... } dispatch_async(dispatch_get_main_queue(),{ // use main thread for UI updates }) } task.resume()
You should use the NSXMLParser
in your completion handler for the request:
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in if data == nil { println("dataTaskWithRequest error: \(error)") return } let parser = NSXMLParser(data: data) parser.delegate = self parser.parse() // you can now check the value of the `success` variable here}task.resume()// but obviously don't try to use it here here
Clearly, the above assumes that you have (a) defined your view controller to conform to NSXMLParserDelegate
and (b) have implemented the NSXMLParserDelegate
methods, e.g. something like:
var elementValue: String?var success = falsefunc parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject]) { if elementName == "success" { elementValue = String() }}func parser(parser: NSXMLParser, foundCharacters string: String?) { if elementValue != nil { elementValue! += string }}func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if elementName == "success" { if elementValue == "true" { success = true } elementValue = nil }}func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) { println("parseErrorOccurred: \(parseError)")}
I have used Class Created below To get Dictionary From XML data.
https://github.com/Bhaavik/BDXmlParser
You need To add that class and just call Below Function for Dictionary response
let objXmlParser = BbXmlParser() let dictResponse = objXmlParser.getdictionaryFromXmlData(data!) print(dictResponse)
And here You go with dictionary. :)