Skip to main content

XPath Example

XPath Example

Consider the following XML document:

<?xml version="1.0"  encoding="UTF-8"?>

<bookstore>

<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>

<book category="web">
<title lang="en">XQuery Tips</title>
<author>Tutorial Reference</author>
<author>Tom Nolan</author>
<author>Ryan Reynolds</author>
<author>James Bond</author>
<year>2022</year>
<price>39.99</price>
</book>

<book category="web">
<title lang="en">Learn XML</title>
<author>Tutorial Reference</author>
<year>2022</year>
<price>9.99</price>
</book>

</bookstore>
note

Using an XMLHttpRequest object to load XML documents is supported in all modern browsers.

var xmlhttp = new XMLHttpRequest();

In the following table there are some path expressions:

Path ExpressionResult
/bookstore/book/titleSelects all the title nodes.
/bookstore/book[1]Selects the first book element that is the child of the bookstore element.
/bookstore/book[1]/titleSelects the title of the first book node under the bookstore element.
/bookstore/book[last()]Selects the last book element that is the child of the bookstore element
/bookstore/book[last()-1]Selects the last but one book element that is the child of the bookstore element
/bookstore/book[position()<3]Selects the first two book elements that are children of the bookstore element
//title[@lang]Selects all the title elements that have an attribute named lang
//title[@lang='en']Selects all the title elements that have a "lang" attribute with a value of "en"
/bookstore/book[price>15.00]Selects all the book elements of the bookstore element that have a price element with a value greater than 15.00.
/bookstore/book[price>15.00]/titleSelects all the title elements of the book elements of the bookstore element that have a price element with a value greater than 15.00.
/bookstore/book/price[text()]Selects the text from all the price nodes.
/bookstore/book[price>25]/priceSelects all the price nodes with a price higher than 25.
/bookstore/book[price<15]/titleSelects all the title nodes with a price lower than 15.

Table of Contents