Swift实现xml解析

作者: Color酸奶 | 来源:发表于2016-02-16 16:32 被阅读3336次

    这里介绍基本的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
    

    相关文章

      网友评论

        本文标题:Swift实现xml解析

        本文链接:https://www.haomeiwen.com/subject/ltnpkttx.html