I am having a hard time trying to create and populate on the fly an NSMutableDictionary from a tree like structure.
Let's say you have a node where
node.attributes
retrieves an NSArray
of key/value pairs
and
node.children
retrieves an NSArray
of nodes from the same node type
how can you convert that tree into a nested NSMutableDictionary
?
my aproach is to try to create a NSMutableDictionary
for each node and populate it with its attributes and children, creating a new NSMutableDictionary
per child and iterate again with it... it sounds like recursion, isn't it
The following code works, for one level deep (parent and children) but throw SIGABRT for grandchildren and beyond.
[self parseElement:doc.rootElement svgObject:&svgData];
where
-(void) parseElement:(GDataXMLElement*)parent svgObject:(NSMutableDictionary**)svgObject
{
NSLog(@"%@", parent.name);
for (GDataXMLNode* attribute in parent.attributes)
{
[*svgObject setObject:attribute.stringValue forKey:attribute.name];
NSLog(@" %@ %@", attribute.name, attribute.stringValue);
}
NSLog(@" children %d", parent.childCount);
for (GDataXMLElement *child in parent.children) {
NSLog(@"%@", child.name);
NSMutableDictionary* element = [[[NSMutableDictionary alloc] initWithCapacity:0] retain];
NSString* key = [child attributeForName:@"id"].stringValue;
[*svgObject setObject:element forKey:key];
[self parseElement:child svgObject:&element];
}
}
UPDATE:
thanks for your answers, I managed to do the code to work
apparently GDataXMLElement doesn't respond to attributeForName when there is no atributes and so my code threw some exeptions, that where dificult to debug being a recursive method
I am taking into account all your (best practice related) sugestions too
Regards