XQuery selection and filtering
The best way to explain XQuery is to say that the relationship of XQuery to XML is equivalent to the relationship of SQL to database tables. XQuery is designed to query XML data-not only for XML files, but also for any data that can be rendered in XML form, including databases.
Select and filter elements
As you saw in the previous section, we use path expressions or FLWOR expressions to select and filter elements.
Look at the following FLWOR expression:
For $x in doc ("books.xml") / bookstore/book where $x/price > 30 order by $x/title return $x/title
For-(optional) bind a variable to each item returned by an in expression
Let-(optional)
Where-(optional) set a condition
Order by-(optional) sets the order of the results
Return-specifies what is returned in the result
For statement
The for statement binds variables to each item returned by an in expression. The for statement produces iterations. There can be multiple FLWOR statements in the same for expression.
To loop a specified number of times in a for statement, you can use the keyword to:
For $x in (1 to 5) return {$x}
Results:
1 2 3 4 5
The keyword at can be used to calculate iterations:
For $x at $i in doc ("books.xml") / bookstore/book/title return {$I}. {data ($x)}
Results:
1. Everyday Italian 2. Harry Potter 3. XQuery Kick Start 4. Learning XML
Multiple in expressions are also allowed in for statements. Use a comma to split each in expression:
For $x in (10 in 20), $y in (100200) return x = {$x} and y = {$y}
Results:
10 and 100 x 10 and y 200 x 20 and y 100 x 20 and y 200
Let statement
The let statement completes variable assignment and avoids repeating the same expression multiple times. The let statement does not cause iterations.
Let $x: = (1 to 5) return {$x}
Results:
1 2 3 4 5
Where statement
The where statement is used to set one or more criteria for the result.
Where $x/price > 30 and $x/price