ios - How do I get a specific element while paring XML? -
i "first subitem" xml document. far works seems store last subitem. program reading straight through xml doc , stopping once finds want. maybe not clear on how stop parsing after has found first item. need tell program stop after finds the first item or add them array , pick out specific part? great.
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 file
class parsethis { var strxmldata:string = "" var currentelement:string = "" var passdata:bool=false var passname:bool=false var itemneeded = "" // set 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 }
a super simplistic way of looking @ need didfindcharacters
, didendelement
. every time didfindcharacters
save them variable. every time end element check whether correct element name , whether it's first of element name type. this:
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 first element of type, save whatever want. finalresultobject = resultstring } resultstring = nil } public func parser(parser: nsxmlparser, parseerroroccurred parseerror: nserror) { //log in debug if to. }
Comments
Post a Comment