Th3sandm4n
Th3sandm4n

Reputation: 809

Xpath having multiple predicate statements

I've looked around and can't seem to find the answer for this. Very simplified:

<a>
  <b>
     <div class=label>
     <label="here"/>
     </div>
  </b>
  <div id="something">
     <b>
        <div class=label>
           <label="here"/>
        </div>
  </div>
</a>

so I'm trying to grab the second "here" label. What I want to do is do the id to get to the "something" part

//.[@id="something”]

and then from that point search for the label with something like

//.[@class="label" and label="here"]

But from reading a few other replies it doesn't appear that something like

//.[@id="something”][@class="label" and label="here"]

works and I was just wondering if I'm just missing something in how it's working? I know I can get the above really simply with another method, it's just an example to ask how to do two predicate statements after each other (if it is indeed possible). Thanks!

Upvotes: 1

Views: 198

Answers (2)

Michael Kay
Michael Kay

Reputation: 163458

The syntax //*[@x='y'] is more idiomatic than //.[@x='y'], probably because it's valid in both XPath 1.0 and XPath 2.0, whereas the latter is only allowed in XPath 2.0. Disallowing predicates after "." was probably an accidental restriction in XPath 1.0, and I think some implementations may have relaxed the restriction, but it's there in the spec: a predicate can only follow either a NodeTest or a PrimaryExpr, and "." is neither.

In XPath 2.0, //* selects all element nodes in the tree, while //. selects all nodes of all kinds (including the document root node), but in this example the effect is the same because the predicate [@x='y'] can only be matched by an element node (for all other node kinds, @x selects nothing and therefore cannot be equal to anything).

Upvotes: 1

Philip Stuyck
Philip Stuyck

Reputation: 7467

I think you need something like this instead :

//.[@id="something”]//.[@class="label" and label="here"]

The point is that the // means : Selects nodes in the document from the current node that match the selection no matter where they are ref : http://www.w3schools.com/xpath/xpath_syntax.asp

Upvotes: 1

Related Questions