Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

XQuery instance


May 28, 2021 XQuery


Table of contents


XQuery instance


In the last section, we covered the syntax rules for XQuery.

In this section, let's study some basic XQuery syntax by looking at an example.


XML instance documentation

We'll use this XML document in the following example.

"books.xml":

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

<bookstore>

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

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

<book category="WEB">
<title >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 >Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>

</bookstore>

View the "books" file .xml your browser.


How do I pick a .xml from "books"?

Function

XQuery uses functions to extract data from XML documents.

doc() to open the "books.xml" file:

doc("books.xml")

The path expression

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

The following path expression is used to pick .xml title elements in the "books" file:

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

(/bookstore picks the bookstore element, /book picks all the book elements under the bookstore element, /title picks all the title elements under each book element)

XQuery above extracts the following data:

<title >Everyday Italian</title>
<title >Harry Potter</title>
<title >XQuery Kick Start</title>
<title >Learning XML</title>

Predicate

XQuery uses predicates to qualify the data extracted from the XML document.

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

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

The XQuery above extracts the following data:

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

That's what you learned about the XQuery basic syntax, and in the next section, you'll learn that if you use FLWOR to pick nodes from the "books.xml" section.