How to parse xml for ios development

So, I know how to parse some XML structures, but I'm currently trying to parse this specific xml structure, which is slightly different from what I'm used to.

I would usually parse something like

<xml> <data> <name>Forrest</name> <age>25</name> <username>forrestgrant</username> </data> </xml> 

But now I am working with some kind of xml, for example ...

 <xml> <data name="Forrest" age="25" username="forrestgrant" /> <other value="6" /> </xml> 

How do I access these variables when they are structured like this? This is how I usually approached this task, which looked for the search for title tags and getting data from each of them. However, now I'm trying to figure out how to parse this different xml style.

 - (void)startTheParsingProcess:(NSData *)parserData { [myDataArray release]; // clears array for next time it is used. myDataArray = [[NSMutableArray alloc] init]; //initalizes the array NSXMLParser *parser = [[NSXMLParser alloc] initWithData:parserData]; //incoming parserDatapassed to NSXMLParser delegate which starts parsing process [parser setDelegate:self]; [parser parse]; //Starts the event-driven parsing operation. [parser release]; } - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { if ([elementName isEqual:@"item"]) { // NSLog(@"Found title!"); itemString = [[NSMutableString alloc] init]; } } - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { [itemString appendString:string]; } - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if ([elementName isEqual:@"item"]) { //NSLog(@"ended title: %@", itemString); [myDataArray addObject:itemString]; //this is where i pass the values over to my array. [itemString release]; itemString = nil; } } - (void)parserDidEndDocument:(NSXMLParser *)parser { // Passes myDataArray to the method that will sort and display the array into a uitableview. [self startSortingTheArray:myDataArray]; } 

Any help would be greatly appreciated.

+4
source share
2 answers

The xml data above provides data as attributes in an xml element.

This callback method gives you access to attributes as a dictionary of key values ​​(attributeDict).

 (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict 

NSLog dictionary in this method to see the values:

 NSLog(@"attributes: %@", attributeDict); 
+3
source

In your didStartItem: method, the attributes dictionary will contain values ​​for all XML attributes.

+1
source

All Articles