XQuery is a functional programming and query language designed for querying and manipulating XML data. Here’s a basic cheat sheet to help you get started with XQuery:
Basics
Select Nodes:
for $node in /path/to/node
return $node
Filter Nodes:
for $node in /path/to/node[condition]
return $node
Select Attribute:
for $attr in /path/to/node/@attribute
return $attr
XPath Functions
String Functions:
substring("hello", 1, 3)
Numeric Functions:
round(3.14159)
Boolean Functions:
not(true())
Sequence Functions:
count(/path/to/nodes)
FLWOR Expressions
FLWOR (For, Let, Where, Order By, Return):
for $item in /path/to/items
where $item/@price > 50
order by $item/@name ascending
return $item
Conditional Expressions
If-Then-Else:
if (/path/to/node[@attribute = 'value'])
then "Yes"
else "No"
Transformation
Construct Element:
element newElement {
attribute attribute1 { "value" },
"content"
}
Modify Element:
replace value of node /path/to/node with "new content"
FLOR
For-Each:
for $item in /path/to/items
return $item
Namespaces
Declare Namespace:
declare namespace ns = "http://example.com";
Use Namespace:
ns:elementName
Document Handling
Load External Document:
doc("external.xml")/path/to/node
Create Document:
document { <root><element>content</element></root> }
Module Import
Import Module:
import module namespace util = "http://example.com/util" at "util.xq";
Call Module Function:
util:customFunction()
Error Handling
Try-Catch:
try {
1 div 0
} catch * {
"Error: Division by zero"
}
Assert:
assert(/path/to/node = 'expected', 'Assertion failed: Not equal to expected value')
Remember to consult the W3C XQuery 3.1 Specification for a comprehensive reference guide. This cheat sheet covers basic XQuery syntax and functions to help you get started with querying and manipulating XML data.