Xquery Syntax in XML
XQuery Syntax in XML
Overview
XQuery syntax is designed to query and transform XML data effectively. It combines elements of XPath for node selection with SQL-like clauses for iteration and filtering.
Basic Structure
for $var in xpath-expressionwhere conditionorder by sorting-expressionreturn expressionfor: Iterates over a sequence of XML nodes.where: Filters nodes based on a condition.order by: Sorts the resulting nodes.return: Defines what to output for each node.
Key Syntax Elements
| Element | Description | Example |
|---|---|---|
| Variables | Begin with $ to store nodes or values | $book := /library/book |
| XPath | Navigate XML elements | /library/book/title |
| FLWOR | Loop/filter/sort/return (for, let, where...) | See above structure |
| Expressions | Use arithmetic, string, boolean, or functions | $book/year > 2000 |
| Literals | Strings "text", numbers 123, booleans true() | "Hello", 123, true() |
| Comments | Single line: (: comment :) | (: This is a comment :) |
Example: Basic XQuery Syntax
Given this XML:
<library> <book> <title>1984</title> <author>George Orwell</author> <year>1949</year> </book> <book> <title>Brave New World</title> <author>Aldous Huxley</author> <year>1932</year> </book></library>XQuery:
for $b in /library/bookwhere $b/year > 1935order by $b/year descendingreturn <book> <title>{ $b/title/text() }</title> <author>{ $b/author/text() }</author> </book>Result:
<book> <title>1984</title> <author>George Orwell</author></book>Summary
XQuery syntax centers around the FLWOR expression.
Use variables with
$.XPath selects nodes.
returnconstructs the output XML or values.Functions and expressions can be embedded.
Need examples of specific syntax elements or help with writing queries?