iwatakeshi
iwatakeshi

Reputation: 697

XML to Object Objective C

I'm trying to convert an XML response from Google to a custom object. My question is what's best to use as in NSMutableArray or NSDictionary when you have a multiple values in i.e. <category> or <title> and how to add them.

<category scheme="http://schemas.google.com/spreadsheets/2006" 
          term="http://schemas.google.com/spreadsheets/2006#spreadsheet"/>
<title type="text">nothing</title>

Upvotes: 1

Views: 3318

Answers (2)

Jasper Blues
Jasper Blues

Reputation: 28766

Marshaling XML onto a NSDictionary will work, however it can result in quite fragile and difficult to maintain code. Two reasons:

  • It will result - 'magic strings' when requesting data. Any change in this string will propagate throughout the code-base.

  • It will be difficult to read, and not exhibit the desirable self-documenting features of good OO.

Instead, its strongly recommended to map the XML of a service payload onto a use-case specific Objective-C object. This is aligned with the principle of contract-first development, meaning that any change to the service might only result in a change to this mapping onto the objective-C object.

A nice XML framework is RaptureXML

Create a category on the RXMLElement class and extract the required information. Then to use the element, just:

RXMLElement* element = [RXMLElement elementWith. . . ];
MyDomesticCat* type = [element asCat];

Upvotes: 3

Ayan Sengupta
Ayan Sengupta

Reputation: 5386

Any XML is ideally a combination on dictionaries and arrays with its root tag initiating a single key dictionary. To take off the overhead of parsing xml to a customized object model you can use the nice framework, XMLReader, available at github.

If you use this framework, your xml parsing becomes as simple as:

NSMutableDictionary* dictionary = [[XMLReader dictionaryForXMLData:<# your xml data #> error:&err] mutableCopy];
NSLog(@"%@",dictionary);
//use dictionary
[dictionary release];

However, you need to pass some well formed xml data as its input. Also you might need to manipulate the content of the parsed dictionary, according to your needs.

Upvotes: 0

Related Questions