Recently, I just got the chance to work on an assignment that requires me to read XML file from the internet and display the fetch data on a simple UITableView. And to be honest, this is the first time I am parsing an XML documents as I am more familiar with the JSON format instead and JSON is fairly simple to work with on an iOS project using the great json-framework open-source library.
There are plenty of resources out there that will do the job very quickly and easily but I opted to try the clean and simple open-source library APXML that does exactly what I like to do – to parse an XML file with minimal effort.
First of all, I need to create a sample XML file which can be found here. This XML file holds sample books with its title, price, authors and description on every node and has a single attribute that holds the bookId.
Content of our sample books.xml is like this:
Reading the XML file and place it in my NSString is pretty straightforward:
For simplicity, I just use ASCII encoding on line 6 but you can quickly change it to UTF if you need to. Just for the demo, this approach loads the XML synchronously and will block the main thread until the XML file has been loaded. And on line 11 is a private method that will call the APXML library to perform the actual parsing of the XML file like this:
With the above code, APDocument initializes with the given XML string and calls its rootElement to determine the root value which is the <catalog> in order tor the parser to determine the object for which it can get all the childElements under it. Child elements is an NSArray of APElement which we can iterate until the last <book> node is read.
APXML library gives you simple method call to get the attribute name:
1: [child valueForAttributeNamed:@"id"]
Or getting the value of each element in a given node (<book>):
1: NSLog(@"Author: %@", [[subElements objectAtIndex:0] value]);
After the method parseBooks has been executed, the usual UITableView will fill-up all the books from our dictionary:
And if you click on each cell, we can display the details of the book with our UIAlertView:
The output of our test project is something like below:
Haven’t tried other XML libraries for iOS yet, but I’m sure APXML will do most of the job on parsing XML file. You could try this cool library also!