0

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];
Centurion
  • 14,106
  • 31
  • 105
  • 197

2 Answers2

1

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

schwa
  • 11,962
  • 14
  • 43
  • 54
  • Well, I have one complain about using xpath: code becomes dependent on xml when using xpath. I mean, I would like to have a universal code parser that parses any depth xml document (does not use attributes). For example, I have 2 xml I need to parse. Both are quite simple: no attributes, just a list of items. But in one xml, every element might have inner elements (children) of tag name "images", and another - "locations". If I use xpath then I'm hardcoding and I will not be able to use the method for other xml. – Centurion Nov 30 '11 at 07:51
0

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

not items

AzabAF
  • 632
  • 1
  • 4
  • 19