Python XQuery & FLWOR Expressions (For, Let, Where, Order, Return)
XQuery is to XML what SQL is to relational databases. It is designed to query collections of XML data. The heart of XQuery is the FLWOR expression: For (iteration), Let (variable assignment), Where (filtering), Order by (sorting), and Return (output construction).
"XQuery is like SQL for nested trees: For is your FROM loop, Where is your WHERE filter, Order by is your ORDER BY clause, and Return is your SELECT projector."
Deep Dive: How It Works
for: Iterates over a sequence of nodes: for $b in doc("books.xml")//book
let: Binds a variable to an entire expression: let $discount := 0.10
where: Filters items matching criteria: where $b/price > 30
order by: Sorts results: order by $b/title
return: Constructs the final XML/HTML output structure: return <item>{$b/title}</item>
Syntax Blueprint
for $x in doc("data.xml")//item
where $x/price > 50
order by $x/name
return <product>{$x/name/text()}</product>Queries XML elements and constructs a fresh transformed XML result tree.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Using = for let variable assignment in XQuery.Why it happens: In XQuery, variable binding uses := (walrus operator), while = is equality comparison.
How to fix: Use let $tax := 0.08 for variable assignment.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Construct a simple XQuery FLWOR return
Write an XQuery snippet: `for $u in //user where $u/age >= 21 return <adult>{$u/name/text()}</adult>`
Finished reading and practicing?
Mark this lesson as completed to update your course progress.