我基于原始答案的整个前提似乎是错误的。如果您使用了以下代码段,
for (CXMLElement *node in nodes) {
NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
int counter;
for(counter = 0; counter < [node childCount]; counter++) {
// common procedure: dictionary with keys/values from XML node
[item setObject:[[node childAtIndex:counter] stringValue] forKey:[[node childAtIndex:counter] name]];
}
[results addObject:item];
[item release];
}
生成您的代码,而不是将social
元素的子项存储为字符串值,并且任何提取它们的合理方法都将丢失。我建议您存储节点而不是创建字典。这是提取评分的示例,
NSString * xmlString = @"<channel> <item> <title> </title> <social> <views> <total_views>2</total_views> </views> <reviews> <average_rating>2</average_rating> </reviews> </social> </item> </channel>";
CXMLDocument * xmlDocument = [[[CXMLDocument alloc] initWithXMLString:xmlString options:0 error:nil] autorelease];
NSArray * nodes = [xmlDocument nodesForXPath:@"//item" error:nil];
for (CXMLElement * node in nodes) {
NSString * title = [[node nodeForXPath:@"title" error:nil] stringValue];
NSString * average_rating = [[node nodeForXPath:@"social/reviews/average_rating" error:nil] stringValue] ;
NSLog(@"%@", title);
NSLog(@"%@", average_rating);
}