Xquery Flwor in XML
XQuery FLWOR Expression in XML
What is FLWOR?
FLWOR is the core expression in XQuery used to query and transform XML data. The name FLWOR is an acronym from its key clauses:
For
Let
Where
Order by
Return
FLWOR Syntax
for $var in expressionlet $var2 := expression2where conditionorder by expression [ascending|descending]return expression3What Each Clause Does
| Clause | Purpose |
|---|---|
| for | Iterates over a sequence of nodes |
| let | Binds variables to expressions (without iteration) |
| where | Filters the sequence based on a condition |
| order by | Sorts the result according to an expression |
| return | Constructs the result for each item in the sequence |
Example XML
<library> <book category="fiction"> <title>The Hobbit</title> <author>J.R.R. Tolkien</author> <year>1937</year> </book> <book category="history"> <title>Sapiens</title> <author>Yuval Noah Harari</author> <year>2011</year> </book> <book category="fiction"> <title>The Lord of the Rings</title> <author>J.R.R. Tolkien</author> <year>1954</year> </book></library>Example FLWOR Query: Get titles of fiction books ordered by year
for $b in /library/bookwhere $b/@category = "fiction"order by $b/year ascendingreturn $b/titleResult:
<title>The Hobbit</title><title>The Lord of the Rings</title>Example with Let Clause
for $b in /library/booklet $title := $b/titlelet $author := $b/authorwhere $b/@category = "fiction"order by $b/year descendingreturn <bookInfo> <title>{ $title/text() }</title> <author>{ $author/text() }</author> </bookInfo>Result:
<bookInfo> <title>The Lord of the Rings</title> <author>J.R.R. Tolkien</author></bookInfo><bookInfo> <title>The Hobbit</title> <author>J.R.R. Tolkien</author></bookInfo>Summary
FLWOR expressions are powerful and flexible for querying XML.
Use for to loop over nodes.
Use let to bind variables.
Use where to filter.
Use order by to sort.
Use return to produce output.
Need help writing or understanding specific FLWOR queries?