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:
ABC Author Name 2020 100.00 XQuery Book Author 1 Author 2 2005 300.00 Sociology 1 Author Name 2010 250.00 Current Affairs Author Name 2004 500.00 Science Book Author 1 Author 2 Author 3 2011 150.00
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{data($x/title)} else{data($x/title)}
Explanation:
Around the if expression, parentheses are required. The else can be just else () but is required.
Result:
ABC XQuery Book Sociology 1 Current Affairs Science Book
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.