如何在削减XML的同时获得特定元素?

时间:2016-02-05 20:39:25

标签: ios xml swift parsing

我只想得到"第一个子项目"来自XML文档。到目前为止一切正常但似乎总是存储最后一个subItem。基本上,程序直接读取XML文档,并在找到我想要的内容后停止。也许我不清楚如何在找到第一项后停止解析。我是否需要告诉程序在找到第一个项目后将其停止或将它们添加到数组然后选择一个特定的部分?任何帮助都会很棒。

XML Doc

<file>main file
     <item>
           <subItem>first subitem</subItem>
     </item>
 </file>
 <file>main file
     <item>
           <subItem>second subitem</subItem>
     </item>
 </file>
 <file>main file
     <item>
           <subItem>third subitem</subItem>
     </item>
 </file>

Swift文件

class parseThis {

 var strXMLData:String = ""
 var currentElement:String = ""
 var passData:Bool=false
 var passName:Bool=false
 var itemNeeded = ""

// set up for parsing 

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

currentElement=elementName;
    if(elementName=="file" || elementName=="item" ||
  elementName=="subItem")

   {
        if(elementName=="subItem"){


        passName=false;
        }
        passData=true;
    }
}

func parser(parser: NSXMLParser, didEndElement elementName: String,
namespaceURI: String?, qualifiedName qName: String?) {
    currentElement="";
currentElement=elementName;
    if(elementName=="file" || elementName=="item" ||
  elementName=="subItem"){

     if(elementName=="subItem"){
      passName=false;
        }
        passData=false;
    }

}
    func parser(parser: NSXMLParser, foundCharacters string: String) {
    if(passName){
        strXMLData=strXMLData+"\n\n"+string
    }

    if(passData)
    {

    itemNeeded = string



}

1 个答案:

答案 0 :(得分:0)

一种超级简单的方法是,您只需要didFindCharactersdidEndElement。每次进入didFindCharacters,您都会将它们保存到变量中。然后每次结束一个元素时,检查这是否是正确的元素名称,以及它是否是该元素名称类型的第一个。像这样:

var resultString : String?
var finalResultObject : String?

public func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
}

public func parser(parser: NSXMLParser, foundCDATA CDATABlock: NSData)
{
    resultString = String(data: CDATABlock, encoding: NSUTF8StringEncoding)
}

public func parser(parser: NSXMLParser, foundCharacters string: String)
{
    if(resultString == nil)
    {
        resultString = ""
    }
    resultString! += string
}

public func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)
{
    if(elementName == "subItem" && finalResultObject == nil)
    {
        //This is your first element of this type, save whatever you want.
        finalResultObject = resultString
    }
    resultString = nil
}

public func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError)
{
    //Log something in debug if you would like to.
}