当嵌套元素出现在xml中时,如何使用TouchXML?我想在NSArray中将图像名称嵌套到字典键@“images”中,但代码有问题:(。这是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>
这是解析代码:
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];
答案 0 :(得分:1)
您不应手动迭代节点。使用XPath总是好几乎。查看TouchXML xpath API。
答案 1 :(得分:0)
resultNodes = [itemListParser nodesForXPath:@“// item”error:nil];
不是物品