Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

XQuery Selection and Filtering

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

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 {$x}

Result:

1

2

3

4

5

The keyword **at** can be used to count iterations:

for $x at $i in doc("books.xml")/bookstore/book/title

return {$i}. {data($x)}

Result:

1. Everyday Italian

2. Harry Potter

3. XQuery Kick Start

4. Learning XML

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 x={$x} and y={$y}

Result:

x=10 and y=100

x=10 and y=200

x=20 and y=100

x=20 and y=200

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 {$x}

Result:

1 2 3 4 5

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:

Harry Potter Everyday Italian Learning XML XQuery Kick Start

return statement:

The return statement specifies what to return.

for $x in doc("books.xml")/bookstore/book

return $x/title

Result:

Everyday Italian Harry Potter XQuery Kick Start Learning XML