使用Swift實現iOS App中解析XML格式資料的教程_Swift

來源:互聯網
上載者:User

在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:001name:Bill Gatesage:15id:002name:Tim Cookage:18

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.