We will use the "bookdetails.xml" document in the example below (same XML file as in the previous chapters).
Selecting and Filtering Elements
As we have seen in the previous chapters, we are selecting
and filtering elements with either a FLWOR expression or with a Path expression .
Look at the FLWOR expression which is given below:
for $x in doc("bookdetails.xml")/bookstore/book
where $x/price>30
order by $x/title
return $x/title
for - (optional) binds the variable to each item returned
by the in expression
let - This one is optional
where - (optional) specify a criteria
order by - (optional) specify the sort-order of the
result
return - specify what to return in the result
The for clause bind a variable to each item returned by the
expression. The for clause result in iteration. There may be
multiple for clauses in the same FLWOR expression.
To loop a
specific number of times in a for clause, you may have to use the to
keyword:
You can use more than one in expression in the for clause.
Use comma to separate the each in expression:
for $x in (10,20), $y in (100,200)
return <test>x={$x} and y={$y}</test>
Result:
<test>x=10 and y=100</test>
<test>x=10 and y=200</test>
<test>x=20 and y=100</test>
<test>x=20 and y=200</test>
The let Clause
The let clause allows variable assignments and it always avoids repeating the same expression many times.
The let clause does not result in an iteration.
let $x := (1 to 5)
return <test>{$x}</test>
Result:
<test>1 2 3 4 5</test>
The where Clause
The where clause is used to specify one or more criteria for the particular result:
where $x/price>30 and $x/price<100
The order by Clause
The order by clause is used to specify the sort order of the results.
Here we want to order the result by the category and title:
for $x in doc("bookdetails.xml")/bookstore/book
order by $x/@category, $x/title
return $x/title