Reading from a XML file in Objective C.

This article presents a useful code snippet for reading from a XML file. Everything can be done in less than 1 minute. First, we need to load our XML file:

-(void)loadDataFromXML
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"myXMLfile" 
                                                     ofType:@"xml"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];

    [parser setDelegate:self];
    [parser parse];
}

Now we have to implement the parse method. Supposing we have a XML file:

<?xml version="1.0"?>
<CATALOG>
    <BOOK title="Quo Vadis" id="45"/>
    <BOOK title="Lord of the Rings" id="23"/>
    <BOOK title="Face" id="16"/>
</CATALOG>

Our parse method can look like:

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
    if ([elementName isEqualToString:@"BOOK"]) 
    {

         NSString* title = [attributeDict valueForKey:@"title"];    
         int id = [[attributeDict valueForKey:@"id"] intValue];
         NSLog(@"Title: %@, ID: %i", title, id);
    }
}

For more about XML parsing see the XML Programming Guide.

About these ads

3 thoughts on “Reading from a XML file in Objective C.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s