Parsing XML with Objective-C (iOS)

In order to parse XML into an NSDictionary to be used in my iOS project, I have found and implemented XMLReader created by Troy Brant.

The implementation is simple to use as you can see for yourself:

NSString *testXMLString = @"<items><item id=\"0001\" type=\"donut\"><name>Cake</name><ppu>0.55</ppu><batters><batter id=\"1001\">Regular</batter><batter id=\"1002\">Chocolate</batter><batter id=\"1003\">Blueberry</batter></batters><topping id=\"5001\">None</topping><topping id=\"5002\">Glazed</topping><topping id=\"5005\">Sugar</topping></item></items>";

// Parse the XML into a dictionary
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:testXMLString error:&parseError];

// Print the dictionary
NSLog(@"%@", xmlDictionary);

For my project however, I needed to parse through some XML returned from a webservice, so I used ASIHTTPRequest, since I was already implementing it for my project.

Ultimately, my code ended up looking like this:

NSURL *url = [NSURL URLWithString:@"http://www.someurl/response.xml"];

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];

[request startSynchronous];

NSError *error = [request error];

if (!error) {

NSString *response = [request responseString];

// NSLog(@"%@", response);

NSError *parseError = nil;

NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:response error:&parseError];

// Print the dictionary

NSLog(@"%@", xmlDictionary);


Still quiet

Leave a Response