Xquery Tutorial
Xquery Tutorial
i
XQuery
This tutorial covers all the basic components of XQuery with suitable examples.
Audience
This tutorial has been prepared for beginners to help them understand the basic
concepts related to XQuery. It provides enough understanding on XQuery from where
you can take yourself to a higher level of expertise.
Prerequisites
Before proceeding with this tutorial, you should have a basic knowledge of XML and
XPath.
All the content and graphics published in this e-book are the property of Tutorials Point
(I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or
republish any contents or a part of contents of this e-book in any manner without written
consent of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely
as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I)
Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of
our website or its contents including this tutorial. If you discover any errors on our
website or in this tutorial, please notify us at [email protected]
i
XQuery
Table of Contents
About the Tutorial ....................................................................................................................................i
Audience ..................................................................................................................................................i
Prerequisites ............................................................................................................................................i
Characteristics .........................................................................................................................................1
Example ..................................................................................................................................................2
Example ..................................................................................................................................................6
Example ..................................................................................................................................................9
Example ................................................................................................................................................11
ii
XQuery
iii
XQuery
Example ................................................................................................................................................44
iv
XQuery
1. XQuery ─ Overview
What is XQuery?
XQuery is a functional language that is used to retrieve information stored in XML
format. XQuery can be used on XML documents, relational databases containing data in
XML formats, or XML Databases. XQuery 3.0 is a W3C recommendation from April 8,
2014.
Characteristics
Functional Language ─ XQuery is a language to retrieve/querying XML based
data.
Benefits of XQuery
Using XQuery, both hierarchical and tabular data can be retrieved.
XQuery can be used to query tree and graphical structures.
XQuery can be directly used to query webpages.
XQuery can be directly used to build webpages.
XQuery can be used to transform xml documents.
XQuery is ideal for XML-based databases and object-based databases. Object
databases are much more flexible and powerful than purely tabular databases.
1
XQuery
We are using an open source standalone XQuery processor Saxon Home Edition (Saxon-
HE) which is widely used. This processor supports XSLT 2.0, XQuery 3.0, and XPath 3.0
and is highly optimized for performance. Saxon XQuery processor can be used without
having any XML database. We'll use a simple XML document as our database in our
examples.
In order to use Saxon XQuery processor, you should have saxon9he.jar, saxon9-test.jar,
saxon9-unpack, saxon9-xqj.jar in your application's classpath. These jar files are
available in the download file SaxonHE9-6-0-1J.zip. Download SaxonHE9-6-0-1J.zip.
Example
We'll use the Java-based Saxon XQuery processor to test books.xqy, a file containing
XQuery expression against our sample XML document, i.e., books.xml.
In this example, we'll see how to write and process a query to get the title elements of
the books whose price is greater than 30.
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book category="JAVA">
<title lang="en">Learn Java in 24 Hours</title>
<author>Robert</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="DOTNET">
<title lang="en">Learn .Net in 24 hours</title>
<author>Peter</author>
<year>2011</year>
<price>40.50</price>
</book>
<book category="XML">
<title lang="en">Learn XQuery in 24 hours</title>
<author>Robert</author>
<author>Peter</author>
2
XQuery
<year>2013</year>
<price>50.00</price>
</book>
<book category="XML">
<title lang="en">Learn XPath in 24 hours</title>
<author>Jay Ban</author>
<year>2010</year>
<price>16.50</price>
</book>
</books>
books.xqy
for $x in doc("books.xml")/books/book
where $x/price>30
return $x/title
XQueryTester.java
package com.tutorialspoint.xquery;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import javax.xml.xquery.XQConnection;
import javax.xml.xquery.XQDataSource;
import javax.xml.xquery.XQException;
import javax.xml.xquery.XQPreparedExpression;
import javax.xml.xquery.XQResultSequence;
import com.saxonica.xqj.SaxonXQDataSource;
3
XQuery
e.printStackTrace();
} catch (XQException e) {
e.printStackTrace();
}
}
E:\java\javac XQueryTester.java
5. Execute XQueryTester
E:\java\java XQueryTester
Output
You'll get the following result:
4
XQuery
5
XQuery
Example
Following is a sample XML document containing the records of a bookstore of various
books.
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book category="JAVA">
<title lang="en">Learn Java in 24 Hours</title>
<author>Robert</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="DOTNET">
<title lang="en">Learn .Net in 24 hours</title>
<author>Peter</author>
<year>2011</year>
<price>70.50</price>
</book>
<book category="XML">
<title lang="en">Learn XQuery in 24 hours</title>
<author>Robert</author>
<author>Peter</author>
<year>2013</year>
<price>50.00</price>
</book>
<book category="XML">
<title lang="en">Learn XPath in 24 hours</title>
<author>Jay Ban</author>
<year>2010</year>
<price>16.50</price>
</book>
</books>
6
XQuery
books.xqy
for $x in doc("books.xml")/books/book
where $x/price>30
return $x/title
Result
<title lang="en">Learn .Net in 24 hours</title>
<title lang="en">Learn XQuery in 24 hours</title>
XQuery Expressions
Let us understand each piece of the above XQuery expression.
Use of functions
doc("books.xml")
doc() is one of the XQuery functions that is used to locate the XML source. Here we've
passed "books.xml". Considering the relative path, books.xml should lie in the same path
where books.xqy is present.
XQuery uses XPath expressions heavily to locate the required portion of XML on which
search is to be made. Here we've chosen all the book nodes available under books node.
XQuery treats xml data as objects. In the above example, $x represents the selected
node, while the for loop iterates over the collection of nodes.
7
XQuery
As $x represents the selected node, "/" is used to get the value of the required element;
"where" clause is used to put a condition on the search results.
As $x represents the selected node, "/" is used to get the value of the required element,
price; "return" clause is used to return the elements from the search results.
8
XQuery
4. XQuery ─ FLWOR
FLWOR is an acronym that stands for "For, Let, Where, Order by, Return". The following
list shows what they account for in a FLWOR expression:
Example
Following is a sample XML document that contains information on a collection of books.
We will use a FLWOR expression to retrieve the titles of those books with a price greater
than 30.
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book category="JAVA">
<title lang="en">Learn Java in 24 Hours</title>
<author>Robert</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="DOTNET">
<title lang="en">Learn .Net in 24 hours</title>
<author>Peter</author>
<year>2011</year>
<price>70.50</price>
</book>
<book category="XML">
<title lang="en">Learn XQuery in 24 hours</title>
<author>Robert</author>
<author>Peter</author>
<year>2013</year>
<price>50.00</price>
9
XQuery
</book>
<book category="XML">
<title lang="en">Learn XPath in 24 hours</title>
<author>Jay Ban</author>
<year>2010</year>
<price>16.50</price>
</book>
</books>
The following Xquery document contains the query expression to be executed on the
above XML document.
books.xqy
let $books := (doc("books.xml")/books/book)
return
{
for $x in $books
where $x/price>30
order by $x/price
return $x/title
}
Result
<title lang="en">Learn XQuery in 24 hours</title>
<title lang="en">Learn .Net in 24 hours</title>
10
XQuery
XQuery can also be easily used to transform an XML document into an HTML page. Take
a look at the following example to understand how XQuery does it.
Example
We will use the same books.xml file. The following example uses XQuery extract data
from books.xml and create an HTML table containing the titles of all the books along with
their respective prices.
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book category="JAVA">
<title lang="en">Learn Java in 24 Hours</title>
<author>Robert</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="DOTNET">
<title lang="en">Learn .Net in 24 hours</title>
<author>Peter</author>
<year>2011</year>
<price>70.50</price>
</book>
<book category="XML">
<title lang="en">Learn XQuery in 24 hours</title>
<author>Robert</author>
<author>Peter</author>
<year>2013</year>
<price>50.00</price>
</book>
<book category="XML">
<title lang="en">Learn XPath in 24 hours</title>
<author>Jay Ban</author>
<year>2010</year>
<price>16.50</price>
11
XQuery
</book>
</books>
Given below is the Xquery expression that is to be executed on the above XML
document.
books.xqy
let $books := (doc("books.xml")/books/book)
return <table><tr><th>Title</th><th>Price</th></tr>
{
for $x in $books
order by $x/price
return <tr><td>{data($x/title)}</td><td>{data($x/price)}</td></tr>
}
</table>
</results>
Result
<table>
<tr>
<th>Title</th>
<th>Price</th>
</tr>
<tr>
<td>Learn XPath in 24 hours</td>
<td>16.50</td>
</tr>
<tr>
<td>Learn Java in 24 Hours</td>
<td>30.00</td>
</tr>
<tr>
<td>Learn XQuery in 24 hours</td>
<td>50.00</td>
</tr>
<tr>
<td>Learn .Net in 24 hours</td>
<td>70.50</td>
12
XQuery
</tr>
</table>
XQuery Expressions
Here we've used the following XQuery expressions:
13
XQuery
6. XQuery ─ XPath
XQuery is XPath compliant. It uses XPath expressions to restrict the search results on
XML collections. For more details on how to use XPath, see our XPath Tutorial.
Recall the following XPath expression which we have used earlier to get the list of books.
doc("books.xml")/books/book
XPath Examples
We will use the books.xml file and apply XQuery to it.
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book category="JAVA">
<title lang="en">Learn Java in 24 Hours</title>
<author>Robert</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="DOTNET">
<title lang="en">Learn .Net in 24 hours</title>
<author>Peter</author>
<year>2011</year>
<price>40.50</price>
</book>
<book category="XML">
<title lang="en">Learn XQuery in 24 hours</title>
<author>Robert</author>
<author>Peter</author>
<year>2013</year>
<price>50.00</price>
</book>
<book category="XML">
<title lang="en">Learn XPath in 24 hours</title>
<author>Jay Ban</author>
<year>2010</year>
14
XQuery
<price>16.50</price>
</book>
</books>
We have given here three versions of an XQuery statement that fulfil the same objective
of displaying the book titles having a price value greater than 30.
XQuery – Version 1
(: read the entire xml document :)
let $books := doc("books.xml")
for $x in $books/books/book
where $x/price > 30
return $x/title
Output
<title lang="en">Learn .Net in 24 hours</title>
<title lang="en">Learn XQuery in 24 hours</title>
XQuery – Version 2
(: read all books :)
let $books := doc("books.xml")/books/book
for $x in $books
where $x/price > 30
return $x/title
Output
<title lang="en">Learn .Net in 24 hours</title>
<title lang="en">Learn XQuery in 24 hours</title>
XQuery – Version 3
(: read books with price > 30 :)
let $books := doc("books.xml")/books/book[price > 30]
for $x in $books
return $x/title
15
XQuery
Output
<title lang="en">Learn .Net in 24 hours</title>
<title lang="en">Learn XQuery in 24 hours</title>
16
XQuery
7. XQuery ─ Sequences
Creating a Sequence
Sequences are created using parenthesis with strings inside quotes or double quotes and
numbers as such. XML elements can also be used as the items of a sequence.
XQuery Expression
let $items := ('orange', <apple/>, <fruit type="juicy"/>, <vehicle
type="car">sentro</vehicle>, 1,2,3,'a','b',"abc")
let $count := count($items)
return
<result>
<count>{$count}</count>
<items>
{
for $item in $items
return <item>{$item}</item>
}
</items>
</result>
Output
<result>
<count>10</count>
<items>
<item>orange</item>
<item>
<apple/>
</item>
<item>
<fruit type="juicy"/>
</item>
<item>
<vehicle type="car">Sentro</vehicle>
17
XQuery
</item>
<item>1</item>
<item>2</item>
<item>3</item>
<item>a</item>
<item>b</item>
<item>abc</item>
</items>
</result>
Output
<result>
<count>6</count>
<items>
<item>2</item>
</items>
</result>
18
XQuery
Output
<result>
<count>6</count>
<items>
<item>1</item>
<item>2</item>
<item>3</item>
</items>
</result>
19
XQuery
The following table lists the commonly used sequence functions provided by XQuery.
count($seq as item()*)
1
Counts the items in a sequence.
sum($seq as item()*)
2
Returns the sum of the items in a sequence.
avg($seq as item()*)
3
Returns the average of the items in a sequence.
min($seq as item()*)
4
Returns the minimum valued item in a sequence.
max($seq as item()*)
5
Returns the maximum valued item in a sequence.
distinct-values($seq as item()*)
6
Returns select distinct items from a sequence.
reverse($seq as item()*)
10
Returns the reversed sequence.
last()
12
Returns the last element of a sequence when used in predicate expression.
position()
13
Used in FLOWR expressions to get the position of an item in a sequence.
20
XQuery
Syntax
count($seq as item()*)
Input Parameters
$seq - provided sequence. A sequence can contain 0 or more items.
Example
XQuery Expression
let $items := (1,2,3,4,5,6)
let $count := count($items)
return
<result>
<count>{$count}</count>
</result>
Output
<result>
<count>6</count>
</result>
Syntax
sum($seq as item()*)
Input Parameters
$seq - provided sequence. A sequence can contain 0 or more items.
21
XQuery
Example
XQuery Expression
let $items := (1,2,3,4,5,6)
let $sum := sum($items)
return
<result>
<sum>{$sum}</sum>
</result>
Output
<result>
<sum>21</sum>
</result>
Syntax
avg($seq as item()*)
Input Parameters
$seq - provided sequence. A sequence can contain 0 or more items.
Example
XQuery Expression
let $items := (1,2,3,4,5,6)
let $avg := avg($items)
return
<result>
<avg>{$avg}</avg>
</result>
22
XQuery
Output
<result>
<avg>3.5</avg>
</result>
Syntax
min($seq as item()*)
Input Parameters
$seq - provided sequence. A sequence can contain 0 or more items.
Example
XQuery Expression
let $items := (1,2,3,4,5,6)
let $min := min($items)
return
<result>
<min>{$min}</min>
</result>
Output
<result>
<min>1</min>
</result>
23
XQuery
Syntax
max($seq as item()*)
Input Parameters
$seq - provided sequence. A sequence can contain 0 or more items.
Example
XQuery Expression
let $items := (1,2,3,4,5,6)
let $max := max($items)
return
<result>
<max>{$max}</max>
</result>
Output
<result>
<max>6</max>
</result>
Syntax
distinct-values($seq as item()*)
Input Parameters
$seq - provided sequence. A sequence can contain 0 or more items.
24
XQuery
Example
XQuery Expression
let $items := (1,2,4,4,5,5)
let $unique-items := distinct-values($items)
return
<result>
<items>
{
for $item in $unique-items
return <item>{$item}</item>
}
</items>
</result>
Output
<result>
<items>
<item>1</item>
<item>2</item>
<item>4</item>
<item>5</item>
</items>
</result>
Syntax
subsequence($seq as item()*, $startingLoc as xs:double, $length as xs:double)
25
XQuery
Input Parameters
$seq - provided sequence. Sequence can contain 0 or more items.
$startingLoc - index of items from which sub-sequence is to be created. Index
starts from 1.
Example
XQuery Expression
let $items := (1,2,3,4,5,6)
let $sub-items := subsequence($items,2,4)
return
<result>
<items>
{
for $item in $sub-items
return <item>{$item}</item>
}
</items>
</result>
Output
<result>
<items>
<item>2</item>
<item>3</item>
<item>4</item>
<item>5</item>
</items>
</result>
26
XQuery
Syntax
insert-before($seq as item()*, $position as xs:integer, $inserts as item()*)
Input Parameters
$seq - provided sequence. Sequence can contain 0 or more items.
$position - index of item where it is to be inserted. Index starts from 1.
$inserts - zero or more items to be inserted.
Example
XQuery Expression
let $items := (1,2,3,4,5,9)
let $additional-items := (6,7,8)
let $new-items := insert-before($items,6,$additional-items)
return
<result>
<items>
{
for $item in $new-items
return >item>{$item}>/item>
}
</items>
</result>
Output
<result>
<items>
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
<item>5</item>
<item>6</item>
27
XQuery
<item>7</item>
<item>8</item>
<item>9</item>
</items>
</result>
Syntax
remove($seq as item()*, $position as xs:integer)
Input Parameters
$seq - provided sequence. Sequence can contain 0 or more items.
$position - index of item where it is to be removed. Index starts from 1.
Example
XQuery Expression
let $items := (1,2,3,4,5,6)
let $new-items := remove($items,4)
return
<result>
<items>
{
for $item in $new-items
return <item>{$item}</item>
}
</items>
</result>
Output
28
XQuery
<result>
<items>
<item>1</item>
<item>2</item>
<item>3</item>
<item>5</item>
<item>6</item>
</items>
</result>
Syntax
reverse($seq as item()*)
Input Parameters
$seq - provided sequence. Sequence can contain 0 or more items.
Example
XQuery Expression
let $items := (1,2,3,4,5,6)
let $new-items := reverse($items)
return
<result>
<items>
{
for $item in $new-items
return <item>{$item}</item>
}
</items>
29
XQuery
</result>
Output
<result>
<items>
<item>6</item>
<item>5</item>
<item>4</item>
<item>3</item>
<item>2</item>
<item>1</item>
</items>
</result>
Syntax
index-of($seq as anyAtomicType()*, $target as anyAtomicType())
Input Parameters
$seq - provided sequence. Sequence can contain 0 or more items.
$target - item whose index is to be returned.
Example
XQuery Expression
30
XQuery
Output
<result>
return <indexof>4</indexof>
</result>
Syntax
last()
Example
XQuery Expression
let $items := (1,2,3,4,5,6)
let $lastElement := $items[last()]
return
<result>
<lastElement>{$lastElement}</lastElement>
</result>
Output
<result>
<lastElement>6</lastElement>
</result>
31
XQuery
Syntax
position()
Example
XQuery Expression
let $items := (1,2,3,4,5,6)
return
<result>
<items>
{
for $item in $items[position() mod 2 eq 1]
return <item>{$item}</item>
}
</items>
</result>
Output
<result>
<items>
<item>1</item>
<item>3</item>
<item>5</item>
</items>
</result>
32
XQuery
The following table lists the commonly used string manipulation functions provided by XQuery.
Syntax
string-length($string as xs:string) as xs:integer
Input Parameters
$string - provided string.
Example
XQuery Expression
let $bookTitle := "Learn XQuery in 24 hours"
let $size := string-length($bookTitle)
return
<result>
<size>{$size}</size>
</result>
Output
<result>
<size>24</size>
</result>
33
XQuery
Syntax
concat($input as xs:anyAtomicType?) as xs:string
Input Parameters
$input - one or more inputs separated by comma.
Example
XQuery Expression
let $bookTitle := "Learn XQuery in 24 hours"
let $updatedTitle := concat($bookTitle,",price: 200$")
return
<result>
<title>{$updatedTitle}</title>
</result>
Output
<result>
<title>Learn XQuery in 24 hours,price: 200$</title>
</result>
34
XQuery
Syntax
string-join($sequence as xs:string*, $delimiter as xs:string) as xs:string
Input Parameters
$sequence - sequence of zero or more strings.
$delimiter - delimiter to separate the items of above sequence.
Example
XQuery Expression
let $fruits :=
<fruits>
<fruit>Apple</fruit>
<fruit>Orange</fruit>
<fruit>Guava</fruit>
<fruit>Pineapple</fruit>
</fruits>
return
<results>
<fruits>{
string-join($fruits/fruit, ',')
}</fruits>
</results>
Output
<results>
<fruits>Apple,Orange,Guava,Pineapple</fruits>
</results>
35
XQuery
The following table lists the commonly used date functions provided by XQuery.
current-date()
1
Returns the current date.
current-time()
2
Returns the current time.
current-dateTime()
3
Returns both the current date and the current time.
Syntax
current-date()
Example
XQuery Expression
let $date := current-date()
return
<results>
<date>{$date}</date>
</results>
Output
<results>
<date>2014-10-27+05:30</date>
</results>
36
XQuery
Syntax
current-time()
Example
XQuery Expression
let $time := current-time()
return
<results>
<time>{$time}</time>
</results>
Output
<results>
<time>14:53:46.803+05:30</time>
</results>
37
XQuery
Syntax
current-dateTime()
Example
XQuery Expression
let $datetime := current-dateTime()
return
<results>
<datetime>{$datetime}</datetime>
</results>
Output
<results>
<datetime>2014-10-27T14:55:58.621+05:30</datetime>
</results>
Here T separates the date with time and +5:30 represents the relative GMT time of the
server.
38
XQuery
The following table lists the commonly used regular expression functions provided by
XQuery.
matches($input, $regex)
1
Returns true if the input matches with the provided regular expression.
tokenize($input, $regex)
3
Returns a sequence of items matching the regular expression.
Syntax
matches($input, $regex)
Input Parameters
$input - input string.
$regex - regular expression.
Example
XQuery Expression
let $input := 'TutorialsPoint Simply Easy Learning'
return (matches($input, 'Hello') = true(),
matches($input, 'T.* S.* E.* L.*') = true()
)
Output
false
true
39
XQuery
Syntax
replace($input, $regex, $string)
Input Parameters
$input - input string.
$regex - regular expression.
$string - string to replace original string.
Example
XQuery Expression
let $input := 'Chapter 1 ... Chapter 2'
return ( replace($input, "Chapter (\d)", "Section $1.0"))
Output
Section 1.0 ... Section 2.0
Syntax
tokenize($input, $regex)
40
XQuery
Input Parameters
$input - input string.
$regex - regular expression.
Example
XQuery Expression
let $input := 'Chapter 1 ... Chapter 2... Section 1.1'
return ( tokenize($input, 'C'))
Output
hapter 1 ...
hapter 2... Section 1.1
41
XQuery
XQuery provides a very useful if-then-else construct to check the validity of the input
values passed. Given below is the syntax of the if-then-else construct.
Syntax
if (condition) then
...
else
...
Example
We will use the following books.xml file and apply to it XQuery expression containing an
if-then-else construct to retrieve the titles of those books with a price value that is
greater than 30.
books.xml
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book category="JAVA">
<title lang="en">Learn Java in 24 Hours</title>
<author>Robert</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="DOTNET">
<title lang="en">Learn .Net in 24 hours</title>
<author>Peter</author>
<year>2011</year>
<price>40.50</price>
</book>
<book category="XML">
<title lang="en">Learn XQuery in 24 hours</title>
<author>Robert</author>
<author>Peter</author>
<year>2013</year>
<price>50.00</price>
42
XQuery
</book>
<book category="XML">
<title lang="en">Learn XPath in 24 hours</title>
<author>Jay Ban</author>
<year>2010</year>
<price>16.50</price>
</book>
</books>
books.xqy
<result>
{
if(not(doc("books.xml"))) then (
<error>
<message>books.xml does not exist</message>
</error>
)
else (
for $x in doc("books.xml")/books/book
where $x/price > 30
return $x/title
)
}
</result>
Output
<result>
<title lang="en">Learn .Net in 24 hours</title>
<title lang="en">Learn XQuery in 24 hours</title>
</result>
43
XQuery
XQuery provides the capability to write custom functions. Listed below are the guidelines
to create a custom function.
Syntax
declare function prefix:function_name($parameter as datatype?...)
as returnDatatype?
{
function body...
};
Example
The following example shows how to create a user-defined function in XQuery.
XQuery Expression
declare function local:discount($price as xs:decimal?,$percentDiscount as
xs:decimal?)
as xs:decimal? {
let $discount := $price - ($price * $percentDiscount div 100)
return $discount
};
Output
90
44
XQuery
45