How to Implement iOS XML Parsing in your iPhone App

Nov 30, 2012 posted by Kellton Tech under Mobillity, Technology

Why XML Parsing:

In many of the iOS application development process, you need to get the data from third party APIs. For example, you have to show user's tweets or Facebook posts on a list view. But the problem is that the receiving data is in XML format or may be in other data format. To make this received data usable, you need to parse it using an appropriate parser. So, if the data received is in XML format, you need to parse it using NSXMLParser or any other XML Parser.

Here we are going to parse the data using NSXMLParser which is in built class provided by Apple.

How to parse data using XML Parsing:

We are going to explain this with the help of simple application. In this application we will read a list, parse the data and then will display the content in list view.

Below is step by step explanation of XML Parsing process for your iPhone app.
1. Create a View based application.
2. Open ViewController.xib and add UITableView to display list of books.


Declare this table view as an outlet and implement all delegates & data-source methods of UITableView.

3. Now open up your viewController's viewDidLoad method and load the data from desired url.

NSURL *url = [[NSURL alloc] initWithString:@""];
parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[parser setDelegate:self];

4. Start parsing data as needed action.
[parser parse];

5. Now configure your view controller for data parsing.
I) Conforms view Controller to NSXMLParserDelegate protocol.
II) Implement following required delegate methods of NSXMLParserDelegate into your viewcontroller .

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

// This delegate method gets called as a new start. In this, we allocate all data which will hold the data.

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {}

// This method gets called when parser found any character between the tags.

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {}

This delegate method gets called when parser is at the end of any tag. In this method, we compare tag names with the help of received "elementName" argument in the method and perform appropriate action on this element.

6. So far we have received and parsed all the data. Now display it on our table view.

7. Build & run your Application. You will get a list displayed as below.


Share this: