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 开发者_StackOverflowfor 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?
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.
There are many parsers there (e.g. XPathQuery, TouchXML etc.).
Hi dontWatchMyProfile, You should better user NSString XML format. For this format, I have a little lib converting easily
http://bcaccinolo.wordpress.com/2010/11/14/xml-to-nsdictionary-converter/
I hope it might help.
Cheers, Benoit
i've not tested this code yet.
http://troybrant.net/blog/2010/09/simple-xml-to-nsdictionary-converter/
精彩评论