开发者

Objective-C nodesForXPath returns all results

开发者 https://www.devze.com 2023-03-16 06:29 出处:网络
this is a follow up to a question I posted yesterday. Given the cars XML example posted below, I run do an xpath query, loop through the results and call \"quickquery - getString\" with the sub eleme

this is a follow up to a question I posted yesterday.

Given the cars XML example posted below, I run do an xpath query, loop through the results and call "quickquery - getString" with the sub element. I would expect that with each iteration of the loop I would get a single element inside the getString function, but I don't. Instead, the nodesForXPath call, inside of the getString function, returns all 4 car 开发者_JAVA百科names, instead of just the one that belongs to that sub element.

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>

This question has been posted before, this is just a cleaner example and code. The title is also more specific.


What you are seeing is correct behaviour for the query "//name". You should use a query relative to the current node, not the root of the document - which is what you are doing.

Take a look at the useful XPath tutorial http://www.w3schools.com/xpath/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号