Easy XML parsing in Swift


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:

[code language=”objc”]
class FirstViewController: UIViewController, NSXMLParserDelegate {

2. Create XMLParser instance:

[code language=”objc”]
var url = NSURL(string: "http://example.com/website-with-xml")
var xmlParser = NSXMLParser(contentsOfURL: url)
xmlParser.delegate = self

3. Implement didStartElement method and do the magic!

[code language=”objc”]
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 odpowiedzi na „Easy XML parsing in Swift”

  1. Awatar gusshely

    thanks for sharing dude 🙂

  2. Awatar 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.

  3. Awatar pawel.dubinski

    Glad I could help. 🙂


    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”

  4. Awatar 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”)
    document.xmlString // returns XML string of the entire document structure

    I hope it will be useful for someone.

  5. Awatar Josh

    You have to create a new parser for every document?

  6. Awatar 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.

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *