在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. } }
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
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。