I am trying to figure out NSXMLParser for my iPhone app and while I generally understand how it works, I am still a little confused about how to extract the values I need.
The XML result that I am parsing is very basic. it is like so:
<start>
<status>300</status>
<record>
<title>The Title</title>
<content>Some content</content>
</record>
</start>
I need to do 3 things:
Get the value of status.
Get the value of content from the first record. There may come a response that offers multiple “record” elements so I need to only get the first.
I can’t figure out how to simply do that. Most all of the examples I have seen involve creating a separate object to populate this data into and I can’t see that being necessary for 2 values. Can anyone tell me how to pull these 2 pieces of data out and only for the first record?
The first thing that happens when the
NSXMLParserencounters an XML tag is that the delegate methodparser:didStartElement:namespaceURI:qualifiedName:attributes:is called; you’ll probably only need to use theelementNamevariable here. Then, the XML parser reads the characters in the tag and callsparser:foundCharacters:with the contents. Finallyparser:didEndElement:namespaceURI:qualifiedNameis called.The approach that I’ve taken, as Apple uses in the SeismicXML examlple, is to use the methods as follows:
parser:didStartElement:namespaceURI:qualifiedName:attributes:, compare the string of the element name to a known value to see if it’s a string you care about. If so, then set an instance variable (anNSMutableString; I’ll call itcontentOfCurrentXMLProperty) to an empty string. Otherwise set it tonil.parser:foundCharacters:, append the found characters tocontentOfCurrentXMLProperty.parser:didEndElement:namespaceURI:qualifiedName, assign the value ofcontentofCurrentXMLPropertyto whatever the appropriate variable is.See the SeismicXML example for more information.
A couple of things about your specific case: first, since the XML parser only returns strings, you’ll need to convert the string to an integer (or whatever data type you’re using) for
status.Second, since you only want the first value for
record, inparser:didStartElement:...I’d set up aBOOLthat flags whether you’ve already seen arecordtag before and, if so, setcontentOfCurrentXMLPropertytonil.