Skip to main content

XQuery First Example

Let's look at an example to learn some basic XQuery

Example

Let's see the following example about a bookstore:

XML File

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>

XQuery Expressions

Following is a sample Xquery document containing the query expression to be executed on the above XML document.

We want the title elements of those XML nodes where the price is greater than 10:

for $x in doc("books.xml")/bookstore/book 
where $x/price>10
return $x/title

and the result is

<title lang="en">Harry Potter</title>
<title lang="en">XQuery Tips</title>

Let's analyze in detail single lines of XQuery code:

Use of functions

XQuery uses functions to extract data from XML documents.

The doc() function is used to open the "books.xml" file:

doc("books.xml")

Use of XPath expressions

XQuery uses path expressions to navigate through elements in an XML document.

The following path expression is used to select all the book elements in the "books.xml" file:

doc("books.xml")/bookstore/book
note
  • /bookstore selects the bookstore element
  • /book selects all the book elements under the bookstore element
  • /title selects all the title elements under each book element

Iterate the objects

XQuery treats XML data as objects. In this snippet, $x represents the selected node, while the for loop iterates over the collection of nodes.

for $x in doc("books.xml")/bookstore/book 

Apply the condition

As $x represents the selected node, / is used to get the value of the required element.

The where clause is used to put a condition on the search results.

where $x/price>10

Return the result

As $x represents the selected node, / is used to get the value of the required element, price, title.

The return clause is used to return the elements from the search results.

return $x/title