Easy XML parsing in Swift
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:
[code language=”objc”]
class FirstViewController: UIViewController, NSXMLParserDelegate {
//(…)
}
[/code]
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
xmlParser.parse()
[/code]
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)")
}
[/code]
Easy, isn’t it?
thanks for sharing dude 🙂
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.
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”
Easy? Not really.
This is what I would call easy:
http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7e72.html
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.
You have to create a new parser for every document?
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.