Search This Blog

Thursday, November 04, 2010

Extending TBXML

Peace be upon you

How are you my beloved reader :)? I hope things is going Ok with you.

today I have added something to the library "TBXML" to extend the functionality to help reading XML in easier way.
Here is link for the library http://tbxml.co.uk/

the functions that I have wrote simply reads the XML and turn it into "Dictionary (Hash table)" the functions that I have wrote neglects the attributes, such code will help transforming the complex hierarchy of XML into dictionary that has key value (the value code be string, array or another dictionary )

Here is the code that I have added to the library (Add this code to the class "TBXML")


+ (NSMutableDictionary*) getXMLNodeInDictionary:(TBXMLElement *)element {

NSMutableDictionary* retDict = [NSMutableDictionary new];

do {

if (element->firstChild) {

if ([retDict valueForKey:[TBXML elementName:element]]==nil) {

[retDict setObject:[self getXMLNodeInDictionary:element->firstChild] forKey:[TBXML elementName:element]];

}else if ([[retDict valueForKey:[TBXML elementName:element]] isKindOfClass:[NSMutableArray class]]) {

[[retDict valueForKey:[TBXML elementName:element]] addObject:[self getXMLNodeInDictionary:element->firstChild]];

}else {

NSMutableArray* arr = [NSMutableArray new];

[arr addObject:[retDict valueForKey:[TBXML elementName:element]]];

[arr addObject:[self getXMLNodeInDictionary:element->firstChild]];

[retDict setObject:[arr autorelease] forKey:[TBXML elementName:element]];

}

}else {

[retDict setObject:[TBXML textForElement:element] forKey:[TBXML elementName:element]];

}

} while ((element = element->nextSibling));

return [retDict autorelease];

}


+ (NSMutableDictionary*)getXMLFileInDictionary:(NSString*)filenameWithFullPath{

NSString* str = [[NSString alloc]initWithContentsOfFile:filenameWithFullPath];

TBXML * tbxml = [TBXML tbxmlWithXMLString:str];

if (!tbxml.rootXMLElement) {

return nil;

}

return [self getXMLNodeInDictionary:tbxml.rootXMLElement];

}




Thanks for your time :)


BR

Ahmed Essam

1 comment:

Murali said...

unfortunatively its not working for the attributes :(

There was an error in this gadget