Latest web development tutorials

XQuery examples

In this section, let us learn by studying an example to some basic XQuery syntax.


XML instance documents

We will use this XML document in the examples below.

"Books.xml":

<?xml version="1.0" encoding="ISO-8859-1"?>

<bookstore>

<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>

<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 Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>

<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>

</bookstore>

See "books.xml" file in your browser .


How to select a node from "books.xml"?

function

XQuery uses functions to extract data from the XML document.

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

doc("books.xml")

Path expression

XQuery uses path expressions to navigate in XML documents through the elements.

The following path expression for "books.xml" select all files in the title element:

doc("books.xml") /bookstore/book/title

(/ Bookstore select bookstore element, / book Selects all book elements under the bookstore element, and / title Selects all title elements under each book element)

The above XQuery can extract the following data:

<title lang="en">Everyday Italian</title>
<title lang="en">Harry Potter</title>
<title lang="en">XQuery Kick Start</title>
<title lang="en">Learning XML</title>

predicate

XQuery uses predicates to define an XML document from the extracted data.

The following predicate is used to select all book elements under the bookstore element, and the value of the price element selected book element under 30 must be less than:

doc("books.xml")/bookstore/book [price<30]

The above XQuery can be extracted to the following data:

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