XQuery Syntax


XQuery is case-sensitive. XQuery elements, attributes, and variables must be valid XML names.


Basic syntax rules of XQuery:

Some basic syntax rules:

  • XQuery is case-sensitive
  • XQuery elements, attributes, and variables must be valid XML names.
  • XQuery string values can use single quotes or double quotes.
  • XQuery variables are defined by a "$" followed by a name, for example, $bookstore
  • XQuery comments are delimited by (: and :), for example, (: XQuery comment :)

XQuery Conditional Expressions

"If-Then-Else" can be used in XQuery.

See the example below:

for $x in doc("books.xml")/bookstore/book
return if ($x/@category="CHILDREN")
then <child>{data($x/title)}</child>
else <adult>{data($x/title)}</adult>

Please note the syntax of "If-Then-Else": the parentheses after the if expression are required. Also, else is required, but just writing "else ()" is acceptable.

The result of the above example:

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


XQuery Comparison

In XQuery, there are two ways to compare values.

  1. General comparison: =, !=, <, <=, >, >=
  2. Value comparison: eq, ne, lt, le, gt, ge

The differences between these two comparison methods are as follows:

Look at the following XQuery expression:

$bookstore//book/@q > 10

If the value of the q attribute is greater than 10, the above expression returns true.

For the following example, if only one q is returned and its value is greater than 10, then the expression returns true. If more than one q is returned, an error occurs:

$bookstore//book/@q gt 10
Other extensions