tags:

views:

1987

answers:

2

The XPath "/bookstore/book[1]" select the first book node under bookstore.

How can I select the first node that matches a more complicated condition, e.g. the first node that matches "/bookstore/book[@location='US']"

+12  A: 

use

/bookstore/book[@location='US'][1]

This will first get the book elements with the location attribute equal to 'US'. Then it will select the first node from that set

(note this is not the same as

/bookstore/book[1][@location='US']

unless the first element also happens to have that location attribute )

Jonathan Fingland
+2  A: 

The alternative to Jonathan Fingland's perfectly valid suggestion is:

/bookstore/book[position() = 1 and @location = 'US']

You can build complex expressions in predicates with the Boolean operators "and" and "or", and with the Boolean XPath functions not(), true() and false(). Plus you can wrap sub-expressions in parentheses.

NOTE:

  • multiple conditions in the same predicate ([position()=1 and @location='US']) must be true as a whole
  • multiple conditions in consecutive predicates ([position()=1][@location='US']) must be true one after another
  • this implies that [position()=1][@location='US'] != [@location='US'][position()=1]
    while [position()=1 and @location='US'] == [@location='US' and position()=1]
  • hint: a lone [position()=1] can be abbreviated to [1]
Tomalak
This would be an alternative to the 2nd xpath code snippet, which Jonathan Fingland noted wouldn't yield the same results. The original post asked for the first node that matched the attrib, but this xpath returns a node if it's the first node and it has that attrib match.
mirezus
@alram: This is true. Thanks for the hint, I've modified my answer to be more clear on this point.
Tomalak