【问题标题】:Objective-C nodesForXPath returns all resultsObjective-C nodesForXPath 返回所有结果
【发布时间】:2011-06-28 05:34:45
【问题描述】:

这是我昨天发布的问题的后续。

鉴于下面发布的汽车 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>

这个问题之前已经发布过,这只是一个更干净的示例和代码。标题也更具体。

【问题讨论】:

    标签: objective-c gdataxml


    【解决方案1】:

    您看到的是查询“//name”的正确行为。您应该使用相对于当前节点的查询,而不是文档的根 - 这就是您正在做的事情。

    看看有用的 XPath 教程http://www.w3schools.com/xpath/

    【讨论】:

    • omw... 我认为您确实做到了。今晚回家后我会进行测试,并告诉你进展如何。谢谢。
    • 感谢您的回答。我将查询更改为 ./name,现在它可以正常工作了。
    猜你喜欢
    • 1970-01-01
    • 2013-06-18
    • 1970-01-01
    • 2013-07-04
    • 2021-06-21
    • 2015-10-23
    • 2012-06-08
    • 2021-01-02
    • 1970-01-01
    相关资源
    最近更新 更多