使用Swift实现iOS App中解析XML格式数据的教程
在IOS中,提供了一套解析XML数据的API。其实也很简单,就是NSXMLParser和NSXMLParserDelegate。
可以直接指定到XML的URL去实例化NSXMLParser
public convenience init?(contentsOfURL url: NSURL)
解析文件,返回的是一次解析的结果
NSXMLParser.parse() -> Bool
监听解析节点的属性
NSXMLParserDelegate.parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])
监听解析节点的内容
NSXMLParserDelegate.parser(parser: NSXMLParser, foundCharacters string: String)
示例:
这里介绍基本的xml数据解析并打印出来.
1.准备xml数据
打开记事本,写下:
<?xml version="1.0" encoding="utf-8" ?> <students> <student id="001"> <name>Bill Gates</name> <age>15</age> </student> <student id="002"> <name>Tim Cook</name> <age>18</age> </student> </students>
保存命名为data.xml.
2.解析xml
在Xcode中新建一个项目,把data.xml导入新建的工程中,直接拖进去好了.在ViewController.swift里写下如下代码:
class ViewController: UIViewController,NSXMLParserDelegate{
override func viewDidLoad() {
super.viewDidLoad()
let parser = NSXMLParser(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("data", ofType: "xml")!))
//1
parser!.delegate = self
parser!.parse()
}
var currentNodeName:String!
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
currentNodeName = elementName
if elementName == "student"{
if let id = attributeDict["id"]{
print("id:\(id)")
}
}
}
func parser(parser: NSXMLParser, foundCharacters string: String) {
//2
let str = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
if str != "" {
print("\(currentNodeName):\(str)")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
代码注释:
1.使用NSXMLParser需要NSXMLParserDelegate代理
2.去除打印如<student>的标签,如果直接写成
func parser(parser: NSXMLParser, foundCharacters string: String) {
print("\(string):\(str)")
}
将会把前面的标签打印出来.
3.代码运行结果
id:001 name:Bill Gates age:15 id:002 name:Tim Cook age:18