iOS XML Parser

Stephen Zaharuk / Wednesday, May 08, 2013

The other day I was doing some coding on the side, and i was playing with different web services. Some of the web services returned JSON, while others returned XML. 

Now, JSON was easy to handle, b/c i could simply use the NSJSONSerialization class built into ios and export it to an NSDictionary. However, XML was a different story. To handle that natively meant that i had to parse it using the NSXMLParser. To do this, you need to create a delegate, and build your data model as you go through each element in the XML. 

Since I was handling all kinds of different markup, i decided i needed a generic solution similar to the native JSON parser. Thus i wrote a custom Xml Parser, which given some NSData, will take that xml, parse it, and return an NSDictionary, letting me treat both JSON and XML the same. 

Instead of keeping the class to myself, i decided to share it with you. So, if you're interested, you can download it HERE.

Obviously this isn't a complete solution, as it depends on how your xml is written. However, its a starting point and should handle a lot of cases. Plus, i'm giving you the code, so you can tweak it to your heart's content. 

To get started, simply add the files to your project. And here is a snippet to show how to use it.

NSData* data = [NSData dataWithContentsOfFile:filePath];

NSDictionary* vals = [IGXMLParser parse:data];

I hope this was helpful!

By Stephen Zaharuk (SteveZ)