Consider this XML Struture:
<api>
<status>200</status>
<message>OK</message>
<response>
<item>
<id>1</id>
<image/>
<title>Some title</title>
<text/>
<email>some email</email>
<channels>
<item>
<id>1</id>
<group_id>1</group_id>
<image>/path/to/image.png</image>
<title>Some other title</title>
<text/>
</item>
<item>
<id>2</id>
<group_id>1</group_id>
<image>/path/to/image.png</image>
<title>Some other title</title>
<text/>
</item>
</item>
</response>
</api>
There could be any number of items under response and any number of items under channels. Actually this structure is used for alot of different data but the generel layout looks like this (but i do not know the names of each xml element.
I have an XML parser (using TBXML parser) and it works great. I want to parse this structure into a combination of nsarrays and nsdictionaries..
Right now i got the following but iam not quite there yet! (and i cant seem to put the finger on what iam missing.
Objective-C code:
- (NSArray*) parsedResponse
{
TBXML *xml = [[TBXML alloc] initWithXMLData:self.responseData];
TBXMLElement *rootXML = xml.rootXMLElement;
NSArray *_data;
if(rootXML != nil)
{
TBXMLElement *xml = [TBXML childElementNamed:@"status" parentElement:rootXML];
if(xml != nil)
_data = [NSArray arrayWithObject:[self traverseElement:xml]];
}
return [_data autorelease];
}
- (NSMutableDictionary*) traverseElement:(TBXMLElement*)_element
{
NSMutableDictionary *_items = [[NSMutableDictionary alloc] init];
if(_element != nil)
{
int i = 0;
do {
if(_element == nil)
continue;
// If there is a firstChild, there is subelements
if(_element->firstChild)
{
//need to do some magic here? i can't figure it out..
NSArray *_item = [NSArray arrayWithObject:[self traverseElement:_element->firstChild]];
NSString *key = [NSString stringWithFormat:@"%@%d", [TBXML elementName:_element], i];
[_items setValue:_item forKey:[TBXML elementName:_element]];
}
else
[_items setValue:[TBXML textForElement:_element] forKey:[TBXML elementName:_element]];
i++;
} while ((_element = _element->nextSibling));
}
return [_items autorelease];
}
Any suggestions?
use NSXMLParser and its delegate methods.
You should refer XML Parsing Guide.