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

XQuery syntax


May 28, 2021 XQuery


Table of contents


XQuery syntax

This section introduces you to the standard syntax rules used in XQuery.

XQuery is case sensitive, and XQuery's elements, properties, and variables must be legitimate XML names.


XQuery's basic syntax rules:

Some basic syntax rules:

  • XQuery is case sensitive
  • XQuery's elements, properties, and variables must be legitimate XML names.
  • XQuery string values can be quoted in single or double quotes.
  • The XQuery variable is defined by "$" and followed by a name, for example, $bookstore
  • XQuery comments are (: and :) Split, for example,(: XQuery comment :)

XQuery conditional expression

If-Then-Else can be used in XQuery.

Take a look at the following example:

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>

Note the syntax of "If-Then-Else": the parenthesis after the if expression is required. Else is also required, but it is also possible to write only "else()".

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. Universal comparison: , ! , slt;, slt;
  2. Comparison of values: eq, ne, lt, le, gt, ge

The differences between the two comparison methods are as follows:

Take a look at the following XQuery expression:

$bookstore//book/@q > 10

If the value of the q property is greater than 10, the return value of the expression above is true.

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

$bookstore//book/@q gt 10

In the next section, we'll learn the basic syntax of XQuery with an example.