Show Menu
Cheatography

XQuery Cheat Sheet (DRAFT) by

XQuery Reference Guide. Information from w3schools.com

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Overview

XQuery is the language for querying XML data
XQuery for XML is like SQL for databases
XQuery is built on XPath expres­sions
XQuery is supported by all major databases
XQuery is a W3C Recomm­end­ation
XQuery is a language for finding and extracting elements and attributes from XML documents.
Here is an example of what XQuery could solve:

"­Select all CD records with a price less than $10 from the CD collection stored in cd_cat­alo­g.x­ml"

FLWOR Expres­sions

For
Selects a sequence of nodes
Let
Binds a sequence to a variable
Where
Filters the nodes
Order by
Sorts the nodes
Return
What to return (gets evaluated once for every node)
Example:
for $x in doc("bo­oks.xm­l")/­boo­kst­ore­/book

where $x/pri­ce>30

order by $x/title

return $x/title

The For Clause

To loop a specific number of times in a for clause, you may use the to keyword.

This
for $x in (1 to 5)

return <te­st>­{$x­}</­tes­t>

Returns
<te­st>­1</­tes­t>

<te­st>­2</­tes­t>

<te­st>­3</­tes­t>

<te­st>­4</­tes­t>

<te­st>­5</­tes­t>


To count the iteration use the at keyword

This
for $x at $i in doc("bo­oks.xm­l")/­boo­kst­ore­/bo­ok/­title

return <bo­ok>­{$i}. {data(­$x)­}</­boo­k>

Returns
<bo­ok>1. Everyday Italia­n</­boo­k>

<bo­ok>2. Harry Potter­</b­ook>

<bo­ok>3. XQuery Kick Start<­/bo­ok>

<bo­ok>4. Learning XML</b­ook>


it is also allowed with more than one expression in the for clause. Use comma to separate each in expres­sion.

This
for $x in (10,20), $y in (100,200)

return <te­st>­x={$x} and y={$y}­</t­est>

Returns
<te­st>x=10 and y=100<­/te­st>

<te­st>x=10 and y=200<­/te­st>

<te­st>x=20 and y=100<­/te­st>

<te­st>x=20 and y=200<­/te­st>

The Let Clause

This
let $x := (1 to 5)

return <te­st>­{$x­}</­tes­t>

Returns
<te­st>1 2 3 4 5</­tes­t>
The let clause allows variable assign­ments and it avoids repeating the same expression many times. The let clause does not result in iteration.

The Where Clause

This
where $x/pri­ce>30 and $x/pri­ce<100
Returns Nodes only where the price is between 30 and 100
The where clause is used to specify one or more criteria for the result.

The order by Clause

This
for $x in doc("bo­oks.xm­l")/­boo­kst­ore­/book

order by $x/@ca­tegory, $x/title

return $x/title

Returns
<title lang="e­n">Harry Potter­</t­itl­e>

<title lang="e­n">E­veryday Italia­n</­title
>
<title lang="e­n">L­earning XML</t­itl­e>

<title lang="e­n">X­Query Kick Start<­/ti­tle>
The order by clause is used to specify the sort order of the result.

The Return Clause

This
for $x in doc("bo­oks.xm­l")/­boo­kst­ore­/book

return $x/title

Returns
<title lang="e­n">E­veryday Italia­n</­tit­le>

<title lang="e­n">Harry Potter­</t­itl­e>

<title lang="e­n">X­Query Kick Start<­/ti­tle>

<title lang="e­n">L­earning XML</t­itl­e>
The return clause specifies what is to be returned.
 

XQuery Basics

doc()
doc("bo­oks.xm­l")
Used to open a file
Path Expres­sions
doc("bo­oks.xm­l")/books­tor­e/b­ook­/title
Used to navigate through elements in an XML document
Predicates
doc("bo­oks.xm­l")/­boo­kst­ore­/book[price­<30]
Used to limit the extracted data

XQuery Basic Syntax Rules

XQuery is case-s­ens­itive
XQuery elements, attrib­utes, and variables must be valid XML names
An XQuery string value can be in single or double quotes
An XQuery variable is defined with a $ followed by a name, e.g. $bookstore
XQuery comments are delimited by (: and :)
(: XQuery Comment :)

Path Expres­sions vs. FLWOR Expres­sions

Path Expression
FLWOR Expression
doc("bo­oks.xm­l")/­boo­kst­ore­/bo­ok[­pri­ce>­30]­/title
for $x in doc("books.xml")/bookstore/book
where $x/price>30
return $x/title
These expres­sions yield the same result.

XQuery Compar­isons

General Compar­isons: =, !=, <, <=, >, >=

$books­tor­e//­book/@q > 10


Returns true if any q attributes have a value greater than 10
Value Compar­isons: eq, ne, lt, le, gt, ge

bookst­ore­//b­ook/@q gt 10


Returns true if there is only one q attribute returned by the expression and its value is greater than 10. If more than one 1 is returned, and error occurs

Examples of Function Calls

Example 1: In an element
<na­me>­{up­per­-ca­se(­$bo­okt­itl­e)}­</n­ame>


Example 2: In the predicate of a path expression
doc("bo­oks.xm­l")/­boo­kst­ore­/bo­ok[­sub­str­ing­(ti­tle­,1,­5)=­'Ha­rry']


Example 3: In a let clause
let $name := (subst­rin­g($­boo­kti­tle­,1,4))
A call to a function can appear where an expression may appear.

User-D­efined Functions

If you cannot find the XQuery function you need, you can write your own. User-d­efined functions can be defined in the query or in a separate library.

Syntax
declare function prefix­:fu­nct­ion­_na­me(­$pa­rameter as datatype)

as return­Dat­atype

{

 ...fun­ction code here...

};


Example: Declared in the Query
declare function local:­min­Pri­ce($p as xs:dec­ima­l?,$d as xs:dec­imal?)

as xs:dec­imal?

{

let $disc := ($p * $d) div 100

return ($p - $disc)

};


How to call the function
<mi­nPr­ice­>{l­oca­l:m­inP­ric­e($­boo­k/p­ric­e,$­boo­k/d­isc­oun­t)}­</m­inP­ric­e>
Note:
Use the declare function keyword.
The name of the function must be prefixed.
The data type of the parameters are mostly the same as the data types defined in XML Schema.
The body of the function must be surrounded by curly braces.

XQuery Termin­ology

Nodes
In XQuery there are 7 kinds: element, attribute, text, namespace, proces­sin­g-i­nst­ruc­tion, comment, and document (root)
Atomic Values
Atomic values are nodes with no children or parent
Items
Items refer to nodes and atomic values
Parent
Each element and attribute has one parent
Children
Element nodes may have 0, 1, or more children.
Siblings
Nodes that have the same parent
Ancestors
A node's parent, parent's parent, etc.
Descen­dants
A node's children, children's children, etc.

XQuery Condit­ional Expres­sions

If-The­n-Else expres­sions are allowed in XQuery

for $x in doc("bo­oks.xm­l")/­boo­kst­ore­/book

return if ($x/@c­ate­gor­y="c­hil­dre­n")

then <ch­ild­>{d­ata­($x­/ti­tle­)}<­/ch­ild>

else <ad­ult­>{d­ata­($x­/ti­tle­)}<­/ad­ult>
Note: "­if-­the­n-e­lse­" syntax: parent­heses around the if expression are required. else is required, but it can be just else ().

Returning HTML

This
for $x in doc("books.xml")/bookstore/book
where $x/price>30
order by $x/title
return $x/title

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

===================================================

This
<ul>
{
for $x in doc("books.xml")/bookstore/book/title
order by $x
return <li>{data($x)}</li>
}
</ul>

Yeilds
<ul>
<li>Everyday Italian</li>
<li>Harry Potter</li>
<li>Learning XML</li>
<li>XQuery Kick Start</li>
</ul>
Note: To eliminate the title element and show only data inside the title element use data($x)

Adding Elements and Attributes to the Result

This
<html>
<body>

<h1>Bookstore</h1>

<ul>
{
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>

Yields
<html>
<body>

<h1>Bookstore</h1>

<ul>
<li>Everyday Italian. Category: COOKING</li>
<li>Harry Potter. Category: CHILDREN</li>
<li>Learning XML. Category: WEB</li>
<li>XQuery Kick Start. Category: WEB</li>
</ul>

</body>
</html>

=======================================

This
<html>
<body>

<h1>Bookstore</h1>

<ul>
{
for $x in doc("books.xml")/bookstore/book
order by $x/title
return <li class="{data($x/@category)}">{data($x/title)}</li>
}
</ul>

</body>
</html>

Yields
<html>
<body>
<h1>Bookstore</h1>

<ul>
<li class="COOKING">Everyday Italian</li>
<li class="CHILDREN">Harry Potter</li>
<li class="WEB">Learning XML</li>
<li class="WEB">XQuery Kick Start</li>
</ul>

</body>
</html>