XQuery SelectandFilter
XML Example Document
We will continue to use this "books.xml" document in the examples below (the same XML file used in the previous chapters).
View the "books.xml" file in your browser。
Selecting and Filtering Elements
As you saw in the previous chapters, we use path expressions or FLWOR expressions to select and filter elements.
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) sets a condition
- order by - (optional) sets the sort order of the results
- return - specifies what to return in the result
for statement
The for statement binds a variable to each item returned by the in expression. The for statement can produce iterations. Multiple for statements can exist in the same FLWOR expression.
To loop a specified number of times in a for statement, you can use the keyword to:
return <test>{$x}</test>
Result:
<test>2</test>
<test>3</test>
<test>4</test>
<test>5</test>
Keywordat can be used to count iterations:
return <book>{$i}. {data($x)}</book>
Result:
<book>2. Harry Potter</book>
<book>3. XQuery Kick Start</book>
<book>4. Learning XML</book>
Multiple in expressions are also allowed in the for statement. Use commas 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>
let statement
The let statement performs variable assignment and can avoid repeating the same expression multiple times. The let statement does not cause iterations.
return <test>{$x}</test>
Result:
where statement
The where statement is used to set one or more conditions (criteria) for the results.
order by statement
The order by statement is used to specify the sort order of the results. Here, we will sort the results 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>
return statement:
The return statement specifies what to return.
return $x/title
Result:
<title lang="en">Harry Potter</title>
<title lang="en">XQuery Kick Start</title>
<title lang="en">Learning XML</title>