Xquery Tutorial
Xquery Tutorial
Xquery Tutorial
Introduction to XQuery
XQuery is to XML what SQL is to database tables.
XQuery is designed to query XML data - not just XML files, but anything that can appear as XML, including
databases.
What is XQuery?
• XQuery is the language for querying XML data
• XQuery for XML is like SQL for databases
• XQuery is built on XPath expressions
• XQuery is supported by all the major database engines (IBM, Oracle, Microsoft, etc.)
• XQuery is a W3C Recommendation
• XQuery is About Querying XML
XQuery is a language for finding and extracting elements and attributes from XML documents.
XQuery Example
"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>
1
<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>
View the "books.xml" file in your browser.
How to Select Nodes From "books.xml"?
Functions
• XQuery uses functions to extract data from XML documents.
• The doc() function is used to open the "books.xml" file:doc("books.xml")
Path Expressions
The following path expression is used to select all the title elements in the "books.xml"
file:doc("books.xml")/bookstore/book/title
(/bookstore selects the bookstore element, /book selects all the book elements under the bookstore element,
and /title selects all the title elements under each book element)
Predicates
XQuery uses predicates to limit the extracted data from XML documents.
The following predicate is used to select all the book elements under the bookstore element that have a
price element with a value that is less than 30:doc("books.xml")/bookstore/book[price<30]
2
Look at the following path expression:
doc("books.xml")/bookstore/book[price>30]/title
The expression above will select all the title elements under the book elements that are under the bookstore
element that have a price element with a value that is higher than 30.
The following FLWOR expression will select exactly the same as the path expression above:for $x in
doc("books.xml")/bookstore/book
where $x/price>30
return $x/title
The expression above will select all the title elements under the book elements that are under the bookstore
element, and return the title elements in alphabetical order.
Now we want to list all the book-titles in our bookstore in an HTML list. We add <ul> and <li> tags to
the FLWOR expression:
<ul>
{
for $x in doc("books.xml")/bookstore/book/title
order by $x
return <li>{$x}</li>
}
</ul>
XQuery Terms
In XQuery, there are seven kinds of nodes: element, attribute, text, namespace, processing-instruction,
comment, and document (root) nodes.
XQuery Terminology
Nodes
3
In XQuery, there are seven kinds of nodes: element, attribute, text, namespace, processing-instruction,
comment, and document (root) nodes. XML documents are treated as trees of nodes. The root of the tree is
called the document node (or root node).
Atomic values
Atomic values are nodes with no children or parent.
Example of atomic values:J K. Rowling
"en"
Items
Items are atomic values or nodes.
Relationship of Nodes
Parent
Each element and attribute has one parent.
In the following example; the book element is the parent of the title, author, year, and price:
<book>
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
Children
Element nodes may have zero, one or more children.
In the following example; the title, author, year, and price elements are all children of the book
element:
<book>
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
Siblings
Nodes that have the same parent.
In the following example; the title, author, year, and price elements are all siblings:
<book>
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
Ancestors
4
A node's parent, parent's parent, etc.
In the following example; the ancestors of the title element are the book element and the bookstore
element:
<bookstore>
<book>
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>
Descendants
A node's children, children's children, etc.
In the following example; descendants of the bookstore element are the book, title, author, year, and
price elements:
<bookstore>
<book>
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>
Now we want to eliminate the title element, and show only the data inside the title element:
<ul>
{
for $x in doc("books.xml")/bookstore/book/title
order by $x
return <li>{data($x)}</li>
}
</ul>
The result will be (an HTML list):<ul>
<li>Everyday Italian</li>
<li>Harry Potter</li>
<li>Learning XML</li>
<li>XQuery Kick Start</li>
</ul>
XQuery Syntax
XQuery is case-sensitive and XQuery elements, attributes, and variables must be valid XML names.
5
• "If-Then-Else" expressions are allowed in XQuery.
XQuery Comparisons
In XQuery there are two ways of comparing values.
1. General comparisons: =, !=, <, <=, >, >=
2. Value comparisons: eq, ne, lt, le, gt, ge
The difference between the two comparison methods are shown below.
The following expression returns true if any q attributes have a value greater than 10:
$bookstore//book/@q > 10
The following expression returns true if there is only one q attribute returned by the expression, and
its value is greater than 10. If more than one q is returned, an error occurs:
$bookstore//book/@q gt 10
The XQuery expression above will include both the title element and the lang attribute in the result,
like this:
<title lang="en">Everyday Italian</title>
<title lang="en">Harry Potter</title>
<title lang="en">Learning XML</title>
<title lang="en">XQuery Kick Start</title>
The XQuery expression above returns the title elements the exact same way as they are described in the
input document.
We now want to add our own elements and attributes to the result!
6
{
for $x in doc("books.xml")/bookstore/book
order by $x/title
return <li>{data($x/title)}. Category: {data($x/@category)}</li>
}
</ul>
</body></html>
7
return $x/title
To loop a specific number of times in a for clause, you may use the to keyword:
for $x in (1 to 5)
return <test>{$x}</test>
Result:
<test>1</test>
<test>2</test>
<test>3</test>
<test>4</test>
<test>5</test>
Result:
<book>1. Everyday Italian</book>
<book>2. Harry Potter</book>
<book>3. XQuery Kick Start</book>
<book>4. Learning XML</book>
It is also allowed with more than one in expression in the for clause. Use comma to separate each in
expression:
for $x in (10,20), $y in (100,200)
return <test>x={$x} and y={$y}</test>
Result:
<test>x=10 and y=100</test>
<test>x=10 and y=200</test>
<test>x=20 and y=100</test>
<test>x=20 and y=200</test>
Result:
<test>1 2 3 4 5</test>
8
return $x/title
Result:
<title lang="en">Harry Potter</title>
<title lang="en">Everyday Italian</title>
<title lang="en">Learning XML</title>
<title lang="en">XQuery Kick Start</title>
XQuery Functions
XQuery 1.0, XPath 2.0, and XSLT 2.0 share the same functions library.
XQuery Functions
XQuery includes over 100 built-in functions. There are functions for string values, numeric values, date and
time comparison, node and QName manipulation, sequence manipulation, Boolean values, and more. You
can also define your own functions in XQuery.
9
Below is an example of how to call the function above:
<minPrice>{local:minPrice($book/price,$book/discount)}</minPrice>
XQuery Summary
This tutorial has taught you how to query XML data.
You have learned that XQuery was designed to query anything that can appear as XML, including
databases.
You have also learned how to query the XML data with FLWOR expressions, and how to construct XHTML
output from the collected data.
XQuery Reference
XQuery 1.0 and XPath 2.0 share the same data model and support the same functions and operators.
XQuery Functions
XQuery is built on XPath expressions. XQuery 1.0 and XPath 2.0 share the same data model and support
the same functions and operators.
• XPath Operators
Below is a list of the operators that can be used in XPath expressions:
+ Addition 6+4 10
- Subtraction 6-4 2
* Multiplication *
10
>= Greater than or equal to price>=9.80 true if price is 9.90
false if price is 9.70
Functions Reference
The default prefix for the function namespace is fn:, and the URI is:
http://www.w3.org/2005/02/xpath-functions.
Accessor Functions
Name Description
Example: string(314)
Result: "314"
fn:codepoints-to-string(int,int,...) Returns a string from a sequence of code points
11
Example: string-to-codepoints("Thérèse")
Result: 84, 104, 233, 114, 232, 115, 101
fn:codepoint-equal(comp1,comp2) Returns true if the value of comp1 is equal to the
value of comp2, according to the Unicode code point
collation (http://www.w3.org/2005/02/xpath-
functions/collation/codepoint), otherwise it returns
false
fn:compare(comp1,comp2) Returns -1 if comp1 is less than comp2, 0 if comp1 is
fn:compare(comp1,comp2,collation) equal to comp2, or 1 if comp1 is greater than comp2
(according to the rules of the collation that is used)
Example:string-join((), 'sep')
Result: ''
fn:substring(string,start,len) Returns the substring from the start position to the
fn:substring(string,start) specified length. Index of the first character is 1. If
length is omitted it returns the substring from the start
position to the end
Example: substring('Beatles',1,4)
Result: 'Beat'
Example: substring('Beatles',2)
Result: 'eatles'
fn:string-length(string) Returns the length of the specified string. If there is no
fn:string-length() string argument it returns the length of the string value
of the current node
Example: string-length('Beatles')
Result: 7
fn:normalize-space(string) Removes leading and trailing spaces from the
fn:normalize-space() specified string, and replaces all internal sequences of
white space with one and returns the result. If there is
no string argument it does the same on the current
node
12
Result: 'the xml'
Example: translate('12:30','30','45')
Result: '12:45'
Example: translate('12:30','03','54')
Result: '12:45'
Example: translate('12:30','0123','abcd')
Result: 'bc:da'
fn:escape-uri(stringURI,esc-res) Example: escape-uri("http://example.com/test#car",
true())
Result: "http%3A%2F%2Fexample.com%2Ftest#car"
Example: escape-uri("http://example.com/test#car",
false())
Result: "http://example.com/test#car"
Example: contains('XML','XM')
Result: true
fn:starts-with(string1,string2) Returns true if string1 starts with string2, otherwise it
returns false
Example: starts-with('XML','X')
Result: true
fn:ends-with(string1,string2) Returns true if string1 ends with string2, otherwise it
returns false
Example: ends-with('XML','X')
Result: false
fn:substring-before(string1,string2) Returns the start of string1 before string2 occurs in it
Example: substring-before('12/10','/')
Result: '12'
fn:substring-after(string1,string2) Returns the remainder of string1 after string2 occurs in
it
Example: substring-after('12/10','/')
Result: '10'
fn:matches(string,pattern) Returns true if the string argument matches the
pattern, otherwise, it returns false
13
Functions on Numeric Values
Name Description
Example: number('100')
Result: 100
fn:abs(num) Returns the absolute value of the argument
Example: abs(3.14)
Result: 3.14
Example: abs(-3.14)
Result: 3.14
fn:ceiling(num) Returns the smallest integer that is greater than the
number argument
Example: ceiling(3.14)
Result: 4
fn:floor(num) Returns the largest integer that is not greater than the
number argument
Example: floor(3.14)
Result: 3
fn:round(num) Rounds the number argument to the nearest integer
Example: round(3.14)
Result: 3
fn:round-half-to-even() Example: round-half-to-even(0.5)
Result: 0
Example: round-half-to-even(1.5)
Result: 2
Example: round-half-to-even(2.5)
Result: 2
fn:resolve-uri(relative,base)
Example: not(true())
Result:
fn:true() Returns the boolean value true
Example: true()
Result: true
14
fn:false() Returns the boolean value false
Example: false()
Result: false
Example: year-from-dateTime(xs:dateTime("2005-01-
10T12:30-04:10"))
Result: 2005
fn:month-from-dateTime(datetime) Returns an integer that represents the month
component in the localized value of the argument
Example: month-from-dateTime(xs:dateTime("2005-
01-10T12:30-04:10"))
Result: 01
fn:day-from-dateTime(datetime) Returns an integer that represents the day component
in the localized value of the argument
Example: day-from-dateTime(xs:dateTime("2005-01-
10T12:30-04:10"))
Result: 10
fn:hours-from-dateTime(datetime) Returns an integer that represents the hours
component in the localized value of the argument
Example: hours-from-dateTime(xs:dateTime("2005-01-
10T12:30-04:10"))
Result: 12
fn:minutes-from-dateTime(datetime) Returns an integer that represents the minutes
component in the localized value of the argument
Example: minutes-from-dateTime(xs:dateTime("2005-
01-10T12:30-04:10"))
Result: 30
fn:seconds-from-dateTime(datetime) Returns a decimal that represents the seconds
component in the localized value of the argument
15
Example: seconds-from-dateTime(xs:dateTime("2005-
01-10T12:30:00-04:10"))
Result: 0
fn:timezone-from-dateTime(datetime) Returns the time zone component of the argument if
any
fn:year-from-date(date) Returns an integer that represents the year in the
localized value of the argument
Example: year-from-date(xs:date("2005-04-23"))
Result: 2005
fn:month-from-date(date) Returns an integer that represents the month in the
localized value of the argument
Example: month-from-date(xs:date("2005-04-23"))
Result: 4
fn:day-from-date(date) Returns an integer that represents the day in the
localized value of the argument
Example: day-from-date(xs:date("2005-04-23"))
Result: 23
fn:timezone-from-date(date) Returns the time zone component of the argument if
any
fn:hours-from-time(time) Returns an integer that represents the hours
component in the localized value of the argument
Example: hours-from-time(xs:time("10:22:00"))
Result: 10
fn:minutes-from-time(time) Returns an integer that represents the minutes
component in the localized value of the argument
Example: minutes-from-time(xs:time("10:22:00"))
Result: 22
fn:seconds-from-time(time) Returns an integer that represents the seconds
component in the localized value of the argument
Example: seconds-from-time(xs:time("10:22:00"))
Result: 0
fn:timezone-from-time(time) Returns the time zone component of the argument if
any
fn:adjust-dateTime-to-timezone(datetime,timezone) If the timezone argument is empty, it returns a
dateTime without a timezone. Otherwise, it returns a
dateTime with a timezone
fn:adjust-date-to-timezone(date,timezone) If the timezone argument is empty, it returns a date
without a timezone. Otherwise, it returns a date with a
timezone
fn:adjust-time-to-timezone(time,timezone) If the timezone argument is empty, it returns a time
without a timezone. Otherwise, it returns a time with a
timezone
16
fn:resolve-QName()
Functions on Nodes
Name Description
fn:name() Returns the name of the current node or the
fn:name(nodeset) first node in the specified node set
fn:local-name() Returns the name of the current node or the
fn:local-name(nodeset) first node in the specified node set - without the
namespace prefix
fn:namespace-uri() Returns the namespace URI of the current
fn:namespace-uri(nodeset) node or the first node in the specified node set
fn:lang(lang) Returns true if the language of the current
node matches the language of the specified language
Example: Lang("en") is true for
<p xml:lang="en">...</p>
Example: Lang("de") is false for
<p xml:lang="en">...</p>
fn:root() Returns the root of the tree to which the
fn:root(node) current node or the specified belongs. This will
usually be a document node
Functions on Sequences
General Functions on Sequences
Name Description
fn:index-of((item,item,...),searchitem) Returns the positions within the sequence of items
that are equal to the searchitem argument
17
Result: (1, 2, 3)
fn:insert-before((item,item,...),pos,inserts) Returns a new sequence constructed from the value
of the item arguments - with the value of the inserts
argument inserted in the position specified by the pos
argument
Example: reverse(("ab"))
Result: ("ab")
fn:subsequence((item,item,...),start,len) Returns a sequence of items from the position
specified by the start argument and continuing for the
number of items specified by the len argument. The
first item is located at position 1
Aggregate Functions
Name Description
fn:count((item,item,...)) Returns the count of nodes
fn:max((arg,arg,...)) Returns the argument that is greater than the others
Example: max((1,2,3))
18
Result: 3
Example: avg((1,2,3))
Result: 2
fn:min((arg,arg,...)) Returns the argument that is less than the others
Example: min((1,2,3))
Result: 1
Context Functions
Name Description
fn:position() Returns the index position of the node that is
currently being processed
Example: //book[position()<=3]
Result: Selects the first three book elements
fn:last() Returns the number of items in the processed node
list
Example: //book[last()]
Result: Selects the last book element
fn:current-dateTime() Returns the current dateTime (with timezone)
fn:current-date() Returns the current date (with timezone)
fn:current-time() Returns the current time (with timezone)
fn:implicit-timezone() Returns the value of the implicit timezone
fn:default-collation() Returns the value of the default collation
By: DataIntegratedEntity
Source: http://w3schools.com/xquery/default.asp
19
20