Reading from a XML file in iOS.

This article presents a useful code snippet for reading from a XML file on iOS.

It shows how to use NSXMLParser to parse XML documents in an event-driven manner using the NSXMLParserDelegate protocol.

How to implement reading from a XML

Let’s say we have a XML file that contains list of books with some additional information about their authors etc. A sample XML document could look like this:

<?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>

Now, let’s think what we’re going to do. Firstly we have to load the XML document. That’s first step to making reading from a XML possible. Secondly, we need to implement a method of NSXMLParserDelegate protocol to parse the document.

Here is our TO-DO list with code, step by step:

  1. Load data from XML file.
    NSString *path = [[NSBundle mainBundle] pathForResource:@"myXMLfile" 
                                                         ofType:@"xml"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    
  2. Create a NSXMLParser.

    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
    
  3. Set up the delegate and start parsing.
    [parser setDelegate:self];
    [parser parse];
    
  4. Implement NSXMLParserDelegate method that parses the document.
    - (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);
        }
    }
    

Full code looks like this. I added a separate method for loading the XML file and starting the parser.

-(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];
}

- (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);
    }
}

That’s how to implement reading from a XML file. For more about XML parsing see the XML Programming Guide.

3 thoughts on “Reading from a XML file in iOS.

Leave a Reply