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?
Dodaj komentarz