NSXMLParser, Two Of The Same Elements Help!
I am trying to parse this XML file for a school project: http://ax.itune开发者_运维问答s.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topsongs/limit=10/genre=20/xml.
My problem is that I am trying to get the Album name which is in here: <im:collection><im:name>
here. However there are two elements called <im:name>
. The first is in the <entry>
, and the second is in the <im:collection>
.
How can I get the information from the second <im:name>
?
You're going to run into the problem all the time with XML as a tag can appear multiple times in multiple parents. The way I track this is to keep track of the parent tag. So, in the subclassed NSXMLParser
, I maintain two properties:
NSString *currentTag;
NSString *parentTag;
In parser:didStartElement:namespaceURI:qualifiedName:attributes:
I populate them:
parentTag = currentTag;
currentTag = elementName;
And in parser:foundCharacters:
I populate my data model according to the parent tag I'm currently in...
if ([currentTag isEqualToString:@"im:name"]) {
if ([parentTag isEqualToString:@"entry"]) {
// do something
} else if ([parentTag isEqualToString:@"im:collection"]) {
// do something else
}
}
Add salt to taste.
In any XML parsing that uses a pull parser (handles tag events instead of browsing through the DOM) you have to set up some kind of variable somewhere that keeps track of where you are in the document if you need elements specific to a subtree of the XML that have the same name as elements in other subtrees.
In your case since you know you want name under collection, you need to also look for the collection tag and keep track of when you have entered and left it - so then when you come to the name tag you only process it if you are also inside collection.
精彩评论