Swift 原生Xml解析

XMLParser解析

1.XML数据

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<person id="1">
    <name>xiaopao</name>
    <age>21</age>
</person>

 

2.实现

 

import UIKit

//遵守XMLParserDelegate协议

class ViewController: UIViewController,XMLParserDelegate {

    //记录当前节点的名字

    var currentNodeName:String!

    override func viewDidLoad() {

        super.viewDidLoad()

        let xmlUrl = URL(fileURLWithPath: Bundle.main.path(forResource: "data", ofType: "xml")!)

        let parser = XMLParser(contentsOf: xmlUrl)

        parser?.delegate = self

        parser?.parse()

    }

    

    //获取节点及属性

    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {

        //记录当前节点

        currentNodeName = elementName

        //打印person节点的id属性及值

        if elementName == "person"{

            if let id = attributeDict["id"]{

                print("id:\(id)")

            }

        }

    }

    //获取节点的文本内容

    func parser(_ parser: XMLParser, foundCharacters string: String) {

        //获取

        let str = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)

        //输出当前节点和文本

        if str != ""{

            print("当前节点:\(currentNodeName!)的文本:\(str)")

        }

    }

}

 

posted @ 2018-06-06 01:15  小炮陈  阅读(1508)  评论(0编辑  收藏  举报