这是我昨天发布的一个问题的后续。
鉴于下面发布的汽车 XML 示例,我运行 xpath 查询,循环遍历结果并使用子元素调用“quickquery - getString”。我希望循环的每次迭代我都会在 getString 函数中得到一个元素,但我没有。相反,在 getString 函数内部的 nodesForXPath 调用返回所有 4 个汽车名称,而不仅仅是属于该子元素的那个。
NSArray *listings = [response nodesForXPath:@"//car" error:&error];
//4 car elements found
if(listings.count > 0)
{
for (GDataXMLElement *listingElement in listings)
{
//printing listingElements description at this point reveales only one car
[QuickQuery getString:listingElement fromXPath:@"//name"];
}
}
//this is defined in QuickQuery class
+(NSString *) getString:(GDataXMLElement *)element fromXPath:(NSString *)xPath
{
NSError *error;
//Query the name element for the spcific car element passed in
NSArray *result = [element nodesForXPath:xPath error:&error]; /// ***THIS CALL
//result.count is 4 at this stage ("BMW", "VW" ... etc)
//out of the 4 calls made to this method, I would expect each value to come up once
//but each time all 4 values are found.
if(result.count > 0)
{
GDataXMLElement *singleValue = (GDataXMLElement *) [result objectAtIndex:0];
return singleValue.stringValue;
}
return nil;
}
<cars>
<car>
<name>VW</name>
</car>
<car>
<name>BMW</name>
</car>
<car>
<name>Mazda</name>
</car>
<car>
<name>Nissan</name>
</car>
</cars>
这个问题之前已经发布过,这只是一个更干净的示例和代码。标题也更具体。