iphoneobjective-ctouchxml

Unable to parse and build nested XML elements with TouchXML


How to use TouchXML when nested elements appear inside xml? I would like need to nest image names inside NSArray for dictionary key @"images", however something is wrong with the code :(. Here's the structure of XML:

<itemList>
  <item>
    <name>SomeName</name>
    <description>Some description</description>
    <images>
        <image>image1.png</image>
        <image>image5.png</image>
    </images>
  </item>
  <item>
    <name>SomeName</name>
    <description>Some description</description>
    <images>
        <image>image1.png</image>
        <image>image5.png</image>
    </images>
  </item>
</itemList>

Here's the parsing code:

resultNodes = [itemListParser nodesForXPath:@"//items" error:nil];

NSMutableDictionary *itemDic = [[NSMutableDictionary alloc] init];
itemList = [[[NSMutableArray alloc] init] autorelease];

NSMutableArray *images = [[NSMutableArray alloc] init];

// Loop through the resultNodes to access each items actual data
for (CXMLElement *resultElement in resultNodes) {

    for(int i = 0; i < [resultElement childCount]; i++) {

        if ([[[resultElement childAtIndex:i] name] isEqualToString:  @"images"]){

            [images removeAllObjects];

            for(int j = 0; j < [[resultElement childAtIndex:i] childCount]; j++) {

                [images addObject:[[resultElement childAtIndex:j] stringValue]];
            }

            [itemDic setObject:images forKey:[[resultElement childAtIndex:i] name]];

        } else {

            [itemDic setObject:[[resultElement childAtIndex:i] stringValue] forKey:[[resultElement childAtIndex:i] name]];
        }

    }
    [itemList addObject:[[itemDic copy] autorelease]]; 
}
[itemDic release];
[images release];

Solution

  • You shouldn't iterate over your nodes manually. It is always almost better to use XPath. Look at the TouchXML xpath APIs.