XQuery vs XPath
Estimated study time: 11 minutes.
XPath and XQuery are closely related — XQuery actually builds on top of XPath — but they serve different purposes and have different levels of expressive power.
XPath: Selecting Nodes
//course[@level='beginner']/title
XPath is a path-based expression language. Given a document, it selects a set of matching nodes. It doesn't have loops, variables, or the ability to construct new output.
XQuery: Querying and Constructing Data
for $c in //course
where $c/@level = 'beginner'
order by $c/title
return <result>{$c/title/text()}</result>
XQuery uses XPath internally to select nodes (the //course part) but adds the ability to filter with full logic, sort, iterate, and construct entirely new XML output — things XPath cannot do on its own.
Key Differences
- Scope — XPath selects; XQuery selects, transforms, and constructs.
- Complexity — XPath expressions are short, single-line paths; XQuery supports full query programs.
- Output — XPath returns a node set; XQuery can output freshly constructed XML or HTML.
- Use case — XPath for simple node selection (e.g. inside XSLT); XQuery for database-style querying across documents.
💡 Tip: If all you need is "find this node," reach for XPath. If you need to filter, join, sort, or reshape data, XQuery is the right tool.