How to select the first element with a specific attribute using XPath

ripper234 picture ripper234 · Jun 17, 2009 · Viewed 437.8k times · Source

The XPath bookstore/book[1] selects 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']

Answer

Jonathan Fingland picture Jonathan Fingland · Jun 17, 2009

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 the use of parentheses, which are required by some implementations.

Note, this is not the same as /bookstore/book[1][@location='US'] unless the first element also happens to have that location attribute.