XQuery Syntax
Learning the rules and structure of XQuery language
⚙️ What is XQuery Syntax?
XQuery syntax defines the rules for writing valid XQuery expressions. It combines path expressions, FLWOR statements, and functions to query and transform XML data with clear, readable code structure.
(: Basic XQuery syntax :)
for $item in //product
where $item/@price < 50
return $item/name
Basic Syntax Rules
XQuery follows specific syntax rules that make queries readable and maintainable. Understanding these rules is essential for writing correct XQuery expressions.
Comments
Document your code
(: This is a comment :)
Variables
Start with $ symbol
let $x := 10
Case Sensitive
Names are case-sensitive
$name ≠ $Name
Strings
Use quotes for text
"Hello" or 'World'
🔹 Path Expression Syntax
Path expressions navigate through XML structure:
(: Absolute path :)
/bookstore/book/title
(: Relative path :)
book/title
(: Descendant path :)
//title
(: With predicate :)
//book[@category="fiction"]/title
- / - Selects from root or direct children
- // - Selects descendants at any level
- @ - Selects attributes
- [ ] - Filters with predicates
🔹 FLWOR Expression Syntax
FLWOR is the most powerful XQuery construct:
(: Complete FLWOR example :)
for $book in //book
let $discount := $book/@price * 0.1
where $book/@price > 20
order by $book/title
return
<discounted>
{$book/title}
<newPrice>{$book/@price - $discount}</newPrice>
</discounted>
- for: Iterates through sequences
- let: Binds variables to values
- where: Filters results
- order by: Sorts results
- return: Specifies output
🔹 Conditional Syntax
Use if-then-else for conditional logic:
(: Simple condition :)
if ($price < 20)
then "Cheap"
else "Expensive"
(: In FLWOR :)
for $book in //book
return
if ($book/@price < 30)
then <affordable>{$book/title}</affordable>
else <premium>{$book/title}</premium>
🔹 Comparison Operators
XQuery provides operators for comparisons:
(: Value comparisons :)
$x eq $y (: equal :)
$x ne $y (: not equal :)
$x lt $y (: less than :)
$x le $y (: less than or equal :)
$x gt $y (: greater than :)
$x ge $y (: greater than or equal :)
(: General comparisons :)
$x = $y
$x != $y
$x < $y
$x > $y
🔹 Constructing XML
Create new XML elements in results:
(: Direct constructor :)
<book>
<title>XQuery Basics</title>
<author>Jane Smith</author>
</book>
(: Computed constructor :)
element book {
element title {"XQuery Basics"},
element author {"Jane Smith"}
}
(: With variables :)
let $title := "XQuery Basics"
return <book><title>{$title}</title></book>
🔹 Arithmetic Operators
Perform calculations in XQuery:
(: Basic arithmetic :)
let $price := 100
let $tax := $price * 0.08
let $total := $price + $tax
return $total
(: Result: 108 :)
(: Operators: +, -, *, div, mod :)
10 + 5 (: 15 :)
10 - 5 (: 5 :)
10 * 5 (: 50 :)
10 div 5 (: 2 :)
10 mod 3 (: 1 :)