使用Swift实现iOS App中解析XML格式数据的教程

2020-01-08 23:09:28丽君

        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教程频道。