dontWatchMyProfile
dontWatchMyProfile

Reputation: 46310

Quick way to get an NSDictionary from an XML NSData representation?

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?

Upvotes: 0

Views: 6682

Answers (4)

Kaz
Kaz

Reputation: 1466

i've not tested this code yet.

http://troybrant.net/blog/2010/09/simple-xml-to-nsdictionary-converter/

Upvotes: 0

Benoit Caccinolo
Benoit Caccinolo

Reputation: 116

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

Upvotes: 1

TechZen
TechZen

Reputation: 64428

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.

Upvotes: 1

Michael Kessler
Michael Kessler

Reputation: 14235

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

Upvotes: 1

Related Questions