Skip to main content

XQuery XPath

XQuery uses XPath expressions to restrict the search results on XML collections.

Let's see an example.

Examples

Consider the following example that contains information about a bookstore.

books.xml
<?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>Tom Nolan</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>

We have given here three versions of an XQuery statement that satisfy the same goal of displaying the titles of books that have a price value of less than 30.

1. Read the entire XML document

The following XQuery document contains the query expression to be executed:

books_ex1.xqy
let $books := doc("books.xml")

for $x in $books/bookstore/book
where $x/price < 30
return $x/title

The result is as follows:

<title lang="en">Harry Potter</title>
<title lang="en">Learn .Net in 24 hours</title>

The result is as follows:

2. Read all the books

The following XQuery document contains the query expression to be executed:

books_ex2.xqy
let $books := doc("books.xml")/bookstore/book

for $x in $books
where $x/price < 30
return $x/title

The result is as follows:

<title lang="en">Harry Potter</title>
<title lang="en">Learn .Net in 24 hours</title>

3. Read books with price lower than 30

The following XQuery document contains the query expression to be executed:

books_ex3.xqy
let $books := doc("books.xml")/bookstore/book[price < 30]

for $x in $books
return $x/title

The result is as follows:

<title lang="en">Harry Potter</title>
<title lang="en">Learn .Net in 24 hours</title>