Basically I have an XML response that is returned and a string, and i need to loops through the xml and store all the information in an array. here is the xml
I wrote recursive function to parse any properly created xml with TBXML library.
In my project I have a class to parse XML. It has a Class Method named: + (id) infoOfElement: (TBXMLElement*) element
How to use:
TBXML *tbxml = [TBXML tbxmlWithXMLData:yourData];
TBXMLElement *rootXMLElement = tbxml.rootXMLElement;
id parsedData = [self infoOfElement: rootXMLElement];
//return NSString or NSDictionary ot NSArray of parsed data
+ (id) infoOfElement: (TBXMLElement*) element
{
if (element->text)
return [TBXML textForElement:element];
NSMutableDictionary *info = [NSMutableDictionary new];
TBXMLAttribute *attribute = element->firstAttribute;
if (attribute) {
do {
[info setValue:[TBXML attributeValue:attribute] forKey:[TBXML attributeName:attribute]];
attribute = attribute -> next;
} while (attribute);
}
TBXMLElement *child = element->firstChild;
if (child){
TBXMLElement *siblingOfChild = child->nextSibling;
//If we have array of children with equal name -> create array of this elements
if ([[TBXML elementName:siblingOfChild] isEqualToString:[TBXML elementName:child]]){
NSMutableArray *children = [NSMutableArray new];
do {
[children addObject:[self infoOfElement:child]];
child = child -> nextSibling;
} while (child);
return [NSDictionary dictionaryWithObject:children forKey:[TBXML elementName:element]];
}
else{
do {
[info setValue:[self infoOfElement:child] forKey:[TBXML elementName:child]];
child = child -> nextSibling;
} while (child);
}
}
return info;
}