Easy XML parsing in Swift

By | July 9, 2014

WARNING:

This tutorial was created with Xcode beta and early version of Swift. Use it at your own risk.

Wondering what is the simplest way to parse small XML resources using Swift? For less demanding purposes you can use standard Foundation library called NSXMLParser.

1. First of all, make your Controller a NSXmlParserDelegate:

class FirstViewController: UIViewController, NSXMLParserDelegate {
//(...)
}

2. Create XMLParser instance:

var url = NSURL(string: "http://example.com/website-with-xml")
var xmlParser = NSXMLParser(contentsOfURL: url)
xmlParser.delegate = self
xmlParser.parse()

3. Implement didStartElement method and do the magic!

func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: NSDictionary!) {
   println("Element's name is \(elementName)")
   println("Element's attributes are \(attributeDict)")
}

Easy, isn’t it?

7 thoughts on “Easy XML parsing in Swift

  1. Metric

    Hey, thank you very much! Helped me a lot.
    Just a small question: I see how we obtain the node’s name and attributes, but how about it’s value? Which is VALUE
    Sorry for stupid question.

  2. pawel.dubinski Post author

    Glad I could help. 🙂

    @Metric:

    Values are stored in “attributeDict” dictionary. For example:

    <place uid=”98606″ lat=”51.1060178592101″ lng=”17.0314425230026″ name=”Fortum” spot=”1″ number=”6118″ bikes=”5+” bike_racks=”16″ bike_numbers=”60130,61176,60098,60065,60045″/>

    elementName is equal to “place”
    attributeDict[“number”] is equal to “6118”

  3. tadija

    I made this new simple and lightweight XML parser for iOS in Swift – https://github.com/tadija/AEXML

    You can use it to read XML data like this:

    let someValue = xmlDocument[“element”][“child”][“anotherChild”].value

    or you can use it to build XML string like this:

    let document = AEXMLDocument()
    let element = document.addChild(“element”)
    element.addChild(“child”)
    document.xmlString // returns XML string of the entire document structure

    I hope it will be useful for someone.

  4. Jason

    I want to parse several lines of latitude and longitude coordinates in an XML document and then create a point at each coordinate on a map view. How would I parse all of the lines of the XML document and plot them on the map? This tutorial appears to just parse one line of XML.

Leave a Reply