首先创建一个xml文件
<data> <person age = "15">ZhangSan</person> <person age = "2">jikexueyuan</person> <a> <b> <c> </c> </b> </a> </data>将xml数据文件导入到文件列表中
随后再代码中 创建xml的解析对象 通知其代理 随后开始解析
import UIKit class ViewController: UIViewController,NSXMLParserDelegate{ override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view,typically from a nib. //创建xml的解析对象 var parser = NSXMLParser(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("data",ofType: "xml")!)) //通知代理 parser?.delegate = self //开始解析 parser?.parse() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //实现代理的方法 来解析数据 var currentNodeName:String? func parser(parser: NSXMLParser,didStartElement elementName: String,namespaceURI: String?,qualifiedName qName: String?,attributes attributeDict: [String : String]) { //获得名字 print(elementName) currentNodeName = elementName //获得属性 if elementName == "person"{ //为了以防有的对象没有age的属性 则要对其进行判断 有没有age的属性 if let age = attributeDict["age"] { print("age:\(age)") } } } //查找当前内容 func parser(parser: NSXMLParser,foundCharacters string: String) { //避免空格符号的出现 var str = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) if str != "" { print("current Node : \(currentNodeName) value is \(str)") } } }
查找到的信息如下所示
age:15
current Node : Optional("person") value is ZhangSan
person
age:2
current Node : Optional("person") value is jikexueyuan
a
b
c
data
c