XQuery Selecting and Filtering
The XML Example Document
We will use the "books.xml" document in the examples below (same XML file as in the previous chapters).
View the "books.xml" file in your browser.
Selecting and Filtering Elements
As we have seen in the previous chapters, we are selecting and filtering elements with either a Path expression or with a FLWOR expression.
Look at the following FLWOR expression:
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) specifies a criteria
- order by - (optional) specifies the sort-order of the result
- return - specifies what to return in the result
The for Clause
The for clause binds a variable to each item returned by the in expression. The for clause results in iteration. There can be multiple for clauses in the same FLWOR expression.
To loop a specific number of times in a for clause, you may use the to keyword:
return <test>{$x}</test>
Result:
<test>2</test>
<test>3</test>
<test>4</test>
<test>5</test>
The at keyword can be used to count the iteration:
return <book>{$i}. {data($x)}</book>
Result:
<book>2. Harry Potter</book>
<book>3. XQuery Kick Start</book>
<book>4. Learning XML</book>
It is also allowed with more than one in expression in the for clause. Use comma to separate each in expression:
return <test>x={$x} and y={$y}</test>
Result:
<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 avoids repeating the same expression many times. The let clause does not result in iteration.
return <test>{$x}</test>
Result:
The where Clause
The where clause is used to specify one or more criteria for the result:
The order by Clause
The order by clause is used to specify the sort order of the result. Here we want to order the result by category and title:
order by $x/@category, $x/title
return $x/title
Result:
<title lang="en">Everyday Italian</title>
<title lang="en">Learning XML</title>
<title lang="en">XQuery Kick Start</title>
The return Clause
The return clause specifies what is to be returned.
return $x/title
Result:
<title lang="en">Harry Potter</title>
<title lang="en">XQuery Kick Start</title>
<title lang="en">Learning XML</title>