XQuery Selection and Filtering
XML example document
We will continue to use this "books.xml" document in the examples below (the same XML file used in the sections above).
View the "books.xml" file in your browser.
Selecting and filtering elements
As seen in previous sections, we use path expressions or FLWOR expressions to select and filter elements.
Please look at the FLWOR expression below:
for $x in doc("books.xml")/bookstore/book
where $x/price>30
order by $x/title
return $x/title
- for - (optional) binds a variable to each item returned by the in expression
- let - (optional)
- where - (optional) sets a condition
- order by - (optional) sets the ordering of the result
- return - specifies what is returned in the result
The for statement
The for statement binds a variable to each item returned by the in expression. The for statement produces iteration. Multiple for statements may exist within the same FLWOR 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
Result:
The keyword **at** can be used to count iterations:
for $x at $i in doc("books.xml")/bookstore/book/title
return
Result:
Multiple in expressions are also allowed in a for statement. Please use a comma to separate each in expression:
for $x in (10,20), $y in (100,200)
return
Result:
let statement
The let statement completes variable assignment and can avoid repeating the same expression multiple times. The let statement does not cause iteration.
let $x := (1 to 5)
return
Result:
where statement
The where statement is used to set one or more conditions (criteria) for the result.
where $x/price>30 and $x/price<100
order by statement
The order by statement is used to specify the sort order of the result. Here, we sort the result by category and title:
for $x in doc("books.xml")/bookstore/book
order by $x/@category, $x/title
return $x/title
Result:
return statement:
The return statement specifies what to return.
for $x in doc("books.xml")/bookstore/book
return $x/title
Result: