XML XQuery
XQuery is to XML what SQL is to relational tables: a query language for searching, filtering, joining and reshaping XML data. It is built on XPath, so every XPath expression you know is already a valid XQuery. On top of that it adds variables, functions and the powerful FLWOR expression.
Note: Browsers do not include an XQuery engine, so the XQuery code on this page is shown as reference rather than run. You'll find XQuery in XML databases (BaseX, eXist-db, MarkLogic), in Saxon, and in SQL Server, Oracle and Db2, which let you query XML columns with it. Below, the same queries are rebuilt with XPath and JavaScript so you can see the results.
Sample data
<shop>
<product id="p1" category="audio"><name>Headphones</name><price>59</price><stock>14</stock></product>
<product id="p2" category="audio"><name>Speaker</name><price>89</price><stock>0</stock></product>
<product id="p3" category="video"><name>Webcam</name><price>45</price><stock>7</stock></product>
<product id="p4" category="video"><name>Ring light</name><price>25</price><stock>22</stock></product>
</shop>Path expressions
The simplest XQuery is just an XPath:
doc("shop.xml")/shop/product[price < 50]/namedoc() loads a document; the rest is XPath.
FLWOR expressions
FLWOR (pronounced "flower") stands for the clauses for, let, where, order by, return:
for $p in doc("shop.xml")/shop/product
let $value := $p/price * $p/stock
where $p/stock > 0
order by $value descending
return <line name="{$p/name}" value="{$value}"/>| Clause | Purpose | SQL analogy |
|---|---|---|
for $x in … |
Loop over a sequence | FROM |
let $y := … |
Bind a value to a variable | computed column |
where … |
Filter | WHERE |
order by … |
Sort | ORDER BY |
return … |
Build each result item | SELECT |
The return clause can construct new XML — { … } inside an element or attribute evaluates an expression, much like template literals in JavaScript.
Here is the same query rebuilt with JavaScript and XPath:
<!DOCTYPE html>
<html>
<body>
<script>
const xml = `<shop>
<product id="p1" category="audio"><name>Headphones</name><price>59</price><stock>14</stock></product>
<product id="p2" category="audio"><name>Speaker</name><price>89</price><stock>0</stock></product>
<product id="p3" category="video"><name>Webcam</name><price>45</price><stock>7</stock></product>
<product id="p4" category="video"><name>Ring light</name><price>25</price><stock>22</stock></product>
</shop>`;
const doc = new DOMParser().parseFromString(xml, 'application/xml');
const val = (node, path) => doc.evaluate(path, node, null, XPathResult.STRING_TYPE, null).stringValue;
const lines = [...doc.querySelectorAll('product')] // for
.map(p => ({ p, value: Number(val(p, 'price')) * Number(val(p, 'stock')) })) // let
.filter(({ p }) => Number(val(p, 'stock')) > 0) // where
.sort((a, b) => b.value - a.value); // order by
for (const { p, value } of lines) { // return
console.log(`<line name="${val(p, 'name')}" value="${value}"/>`);
}
</script>
</body>
</html>Grouping and aggregating
XQuery 3 has a group by clause and the usual aggregate functions:
for $p in doc("shop.xml")//product
group by $cat := $p/@category
order by $cat
return
<category name="{$cat}" products="{count($p)}" avgPrice="{avg($p/price)}"/>Result:
<category name="audio" products="2" avgPrice="74"/>
<category name="video" products="2" avgPrice="35"/>Conditional expressions and functions
declare function local:label($price as xs:decimal) as xs:string {
if ($price >= 50) then "premium" else "budget"
};
for $p in doc("shop.xml")//product
return concat($p/name, ": ", local:label($p/price))<!DOCTYPE html>
<html>
<body>
<script>
const xml = `<shop>
<product category="audio"><name>Headphones</name><price>59</price></product>
<product category="audio"><name>Speaker</name><price>89</price></product>
<product category="video"><name>Webcam</name><price>45</price></product>
<product category="video"><name>Ring light</name><price>25</price></product>
</shop>`;
const doc = new DOMParser().parseFromString(xml, 'application/xml');
const label = (price) => price >= 50 ? 'premium' : 'budget';
for (const p of doc.querySelectorAll('product')) {
const price = Number(p.querySelector('price').textContent);
console.log(`${p.querySelector('name').textContent}: ${label(price)}`);
}
</script>
</body>
</html>XQuery vs XSLT
Both can query and transform XML, and both build on XPath. XQuery feels like a query language (short, expression-based, great for databases and reports). XSLT feels like a rule-based transformation language (great for turning whole documents into other documents). Many teams use both.
Tip: XQuery is case-sensitive, and all its keywords are lowercase:
for,let,where,return.
Test yourself
What does FLWOR stand for?
- Find, Link, Write, Order, Read
- For, Let, Where, Order by, Return
- Filter, Loop, While, Output, Return
- From, Limit, Where, Order, Run
Which language is XQuery built on?
- SQL
- XPath
- CSS selectors
- JSONPath