XQuery Syntax

There are some syntax rules defined for XQuery, such as, it is case-sensitive and that the elements, attributes, and variables in XQuery must be valid XML names.

XQuery Basic Syntax Rules:

  • Case-sensitive.
  • Elements, attributes, and variables must be valid XML names.
  • The string value can be in single or double-quotes.
  • Variable is defined with a $ followed by a name, e.g. $book.
  • Comments are delimited by (: and :), e.g. (: I am a Comment :).

Books.xml:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
 
  <book category="Child">
    <title lang="en">ABC</title>
    <author>Author Name</author>
    <year>2020</year>
    <price>100.00</price>
  </book>
 
  <book category="IT">
    <title lang="en">XQuery Book</title>
    <author>Author 1</author>
    <author>Author 2</author>
 <year>2005</year>
    <price>300.00</price>
  </book>
 
  <book category="Sociology">
    <title lang="en">Sociology 1</title>
    <author>Author Name</author>
 <year>2010</year>
    <price>250.00</price>
  </book>
 
  <book category="GK">
    <title lang="en">Current Affairs</title>
    <author>Author Name</author>
 <year>2004</year>
    <price>500.00</price>
  </book>
 
  <book category="Science">
    <title lang="en">Science Book</title>
    <author>Author 1</author>
    <author>Author 2</author>
    <author>Author 3</author>
 <year>2011</year>
    <price>150.00</price>
  </book>
 
</bookstore>

XQuery Conditional Expressions:

In XQuery, “If-Then-Else” expressions are allowed.

Example:

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

Explanation:

Around the if expression, parentheses are required. The else can be just else () but is required.

Result:

<child>ABC</child>
<adult>XQuery Book</adult>
<adult>Sociology 1</adult>
<adult>Current Affairs</adult>
<adult>Science Book</adult>

XQuery Comparisons:

We can compare values in XQuery, using either of the two ways:

1. General comparisons:

=, !=, <, <=, >, >=

2. Value comparisons:

eq, ne, lt, le, gt, ge

Difference between the two comparison methods:

Example 1:

$bookstore//book/@q > 10

Explanation:

In the above example, we are using a comparison expression to return a true value if any q attributes have a value greater than 10.

Example 2:

$bookstore//book/@q gt 10

Explanation:

In the above example, we are using a comparison expression to return a true value if there is only one q attribute returned by the expression. The value of q should be greater than 10. Here, an error occurs, if more than one q is returned.

Please Share