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']"
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']"
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 )
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:
[position()=1 and @location='US']
) must be true as a whole[position()=1][@location='US']
) must be true one after another[position()=1][@location='US']
!= [@location='US'][position()=1]
[position()=1 and @location='US']
== [@location='US' and position()=1]
[position()=1]
can be abbreviated to [1]