我正在尝试使用XMLparser快速解析来自服务器的xml文件,
我有一个var m_items,它是一个NSMutableArray和一个具有
的CItemData对象 var m_id:String = ""
var m_type:CLong = CLong(0)
var m_title:String = ""
var m_description:String = ""
var m_data:String = ""
override init()
{
super.init();
}
init(id: String, title:String, type:CLong) {
self.m_id = id;
self.m_title = title;
self.m_type = type;
这是一个XML,其项目根为项目ID,并包含诸如标题,描述和数据之类的一些值。
<items>
<item id="1" type="1">
<title>
<![CDATA[ Definition of Hacker ]]>
</title>
<description>
<![CDATA[ Description 1 ]]>
</description>
<data>
<![CDATA[ Data 1 ]]>
</data>
</item>
</items>
我试图这样解析,但是我不明白如何正确使用didstartelement。有什么帮助吗?我的代码来自示例,但不符合我的需求。问题是
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String])
{
var attr:String = ""
if(elementName == "items")
{
self.m_root = CItemData();
self.m_last_node = self.m_root;
}
else if(elementName == "item")
{
attr = attributeDict["id"]!
let item:CItemData = CItemData()
item.m_id.setObject(attr , forKey: "id" as NSCopying)
self.m_root?.m_id.add(item)
self.m_last_item = item;
self.m_last_node = item;
}
else if(elementName == "child")
{
attr = attributeDict["id"]!
let child:CItemData = CItemData()
child.m_type.setObject(attr , forKey: "id" as NSCopying)
self.m_last_item?.m_type.add(child)
self.m_last_node = item;
}
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if(elementName == "title")
{
self.m_last_node?.m_title = self.m_last_string
}
else if(elementName == "description"){
self.m_last_node?.m_description = self.m_last_string
}
else if(elementName == "data"){
self.m_last_node?.m_data = self.m_last_string
}
}
func parser(_ parser: XMLParser, foundCharacters string: String)
{
self.m_last_string = string;
}
}