XQuery Selection and Filtering
- Previous Page XQuery Add
- Next Page XQuery Functions
XML Example Document
We will continue to use this "books.xml" document in the following examples (the same as the XML file used in the previous chapters).
Select and filter elements
As seen in the previous chapters, we use path expressions or FLWOR expressions to select and filter elements.
Please see 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) Set the order of the results
- return
- Specifies the content returned in the result
for statement
The for statement binds a variable to each item returned by an in expression. The for statement can produce iterations. Multiple for statements can exist within the same FLWOR expression.
To specify a number of iterations in a for statement, you can useKeyword to :
for $x in (1 to 5) return <test>{$x}</test>
Results:
<test>1</test> <test>2</test> <test>3</test> <test>4</test> <test>5</test>
Keyword at Can be used to calculate iterations:
for $x at $i in doc("books.xml")/bookstore/book/title return <book>{$i}. {data($x)}</book>
Results:
<book>1. Everyday Italian</book> <book>2. Harry Potter</book> <book>3. XQuery Kick Start</book> <book>4. Learning XML</book>
Similarly in the for statementMultiple in expressions are allowedPlease use commas to separate each in expression:
for $x in (10,20), $y in (100,200) return <test>x={$x} and y={$y}</test>
Results:
<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>
let statement
The let statement can perform variable assignments and can avoid repeating the same expression multiple times. The let statement does not cause iteration.
let $x := (1 to 5) return <test>{$x}</test>
Results:
<test>1 2 3 4 5</test>
Where Statement
The where statement is used to set one or more conditions (criteria) for the results.
where $x/price>30 and $x/price<100
Order by Statement
The order by statement is used to specify the order of the results. Here, we want to sort the results by category and title:
for $x in doc("books.xml")/bookstore/book order by $x/@category, $x/title return $x/title
Results:
<title lang="en">Harry Potter</title> <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 the content to be returned.
for $x in doc("books.xml")/bookstore/book return $x/title
Results:
<title lang="en">Everyday Italian</title> <title lang="en">Harry Potter</title> <title lang="en">XQuery Kick Start</title> <title lang="en">Learning XML</title>
- Previous Page XQuery Add
- Next Page XQuery Functions