views:

98

answers:

2

I've loaded an XML file as NSData into memory and parse over the elements using NSXMLParser. Although it works, it's a very ugly and hard to maintain code since there are about 150 different elements to parse.

I know there are nice third-party solutions, but I want to keep it with the iPhone SDK for purpose of practice and fun.

So I thought: Why not convert that XML file into an NSDictionary? Having this, I could use fast enumeration to go over the elements.

Or is it just the same amount of ugly code needed to parse and process an XML right away with NSXMLParser?

Would I build up an NSDictionary for every found node in the XML and create a huge one, containing the whole structure and data? Or is there an even simpler way?

+1  A: 

There are many parsers there (e.g. XPathQuery, TouchXML etc.).

Michael Kessler
How about NSXMLParser that comes shipped with the iPhone SDK? What are the other ones doing different?
dontWatchMyProfile
With NSXMLParser you will have to build the objects hierarchy all by your self. The 3-rd party parsers usually return an object (NSArray or NSDictionary) that holds the entire hierarchy in objects like NSArray and NSDictionary. In addition, usually the 3-rd party parsers usually built upon the libxml and not the NSXMLParser - libxml is faster. One more thing - as far as I know you can't use the NSXMLParser to parse a local file, but maybe I'm wrong on this one...
Michael Kessler
+1  A: 

NSDictionary cannot read any random xml format. It can only read xml in a specific format which is the plist format.

The plist actually predates xml and the current plist format is just an xml version of the original. The name plist is a contraction of "property list" as the files define the properties of an instance of a class. Therefore, all the xml tags in the file must define elements of an instance of class that implements the NSCoder protocol.

So, yes, if you start with arbitrary xml you must laboriously parse it to convert it into an NSDictionary or some other class.

I wouldn't bother writing a parser from scratch for any reason except as a learning exercise. Every single xml format requires a different parser. It's better to use an existing parser so that 80% of the work is done for you. In a real project, you will end up doing that anyway.

TechZen