Parse XML for iPhone NSXMLParser

so here's how you parse an xml file in objective c, you include the xml in you resources folder in xcode and then we'll create a class file which acts as an NXMLParserDelegate to parse the file and call specific methods we'll need to get the xml attributes.

So if our xml looks something like this:

[code lang="xml"]









[/code]

We have to make a class that acts as an NXMLParserDelegate so the .h file would look something like this:

[code lang="c"]
@interface myXMLParser : NSObject
{
}
- (void)parseXMLFile:(NSString *)pathToFile;
@end
[/code]

Then in the .m file we'll have the parseXMLFile method which takes a path to the xml file:

[code lang="c"]
- (void)parseXMLFile:(NSString *)pathToFile
{
BOOL success;
NSXMLParser *addressParser;

NSURL *xmlURL = [NSURL fileURLWithPath:pathToFile];
if (addressParser) // addressParser is an NSXMLParser instance variable
[addressParser release];
addressParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
[addressParser setDelegate:self];
[addressParser setShouldResolveExternalEntities:YES];
success = [addressParser parse]; // return value not used
// if not successful, delegate is informed of error
}

// Start of element
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
attributes:(NSDictionary *)attributeDict
{
if ( [elementName isEqualToString:@"level"] ) {
//currentPerson = [[NSObject alloc] init];
return;
}

if ( [elementName isEqualToString:@"bird"] ) {
NSString *color = [attributeDict objectForKey:@"color"];
NSLog(@"bird %@", color);
return;
}
}
[/code]

So what we were doing is going through the elements and searching for the ones that match what we are looking for, then we can add them to objects or do whatever logic we need.

To implement this class we just need to allocate it and pass it the path to the file

[code lang="c"]
BirdXML *birdXML = [BirdXML alloc];
[birdXML parseXMLFile:[[NSBundle mainBundle] pathForResource:@"myxmlfilename" ofType:@"xml"]];
[/code]

That's pretty much the gist of it!

Leave a Reply

Your email address will not be published. Required fields are marked *