運用Swift完成iOS App中解析XML格式數據的教程。本站提示廣大學習愛好者:(運用Swift完成iOS App中解析XML格式數據的教程)文章只能為提供參考,不一定能成為您想要的結果。以下是運用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