XQuery/FLWOR Expression
From Wikibooks, the open-content textbooks collection
[edit] Motivation
You have a sequence of items and you want to create a report that contains these items.
[edit] Method
We will use a basic XQuery FLWOR expression to iterate through each of the items in a sequence. The five parts of a FLWOR expression are:
- for - specifies what items in the sequence you want to select
- let - used to create temporary names used in the return (optional)
- where - limit items returned (optional)
- order - change the order of the results (optional)
- return - specify the structure of the data returned (required)
Here is a simple example of a FLWOR expression:
for $book in doc("catalog.xml")/books/book
let $title := $book/title/text()
let $price := $book/price/text()
where xs:decimal($price) gt 50.00
order by $title
return
<book>
<title>{$title}</title>
<price>{$price}</price>
</book>
This XQuery FLWOR expression will return all books that have a price over $50.00. Note that we have not just one but two let statements after the for loop. We also add a where clauses to restrict the results to books over $50.00. The results are sorted by the title and the result is a new sequence of book items with both the price and the title in them.
[edit] Using the "to" function to generate a range of values
You can also express a range of values from one number to another number by placing the keyword "to" between two numbers in a sequence.
The following generates a list of values from 1 to 10.
xquery version "1.0"; <list> {for $i in (1 to 10) return <value>{$i}</value> } </list>