Finding the First Node That Meets a Condition

Suppose you want to obtain from a collection the first node that meets a certain condition. For example, you want the first book whose author's last name is Bob. You can specify the following query:

(//book[author/last-name="Bob"])[position()=1]
               

            

When the XPath processor evaluates this expression, it creates a collection of book elements where the author's last name is Bob. The XPath processor then returns the first node in this collection.

The following two expressions appear to also return the first book whose author's last name is Bob, but they do not. Instead, these queries both return a book whose author's last name is Bob only if that book is the first book in the document.

//book[author/first-name="Bob"][position()=1]
               
//book[author/first-name="Bob" and position() = 1]
               

            

 
Free Stylus Studio XML Training:
W3C Member