XQuery Reference

Prolog & Modules

The prolog is everything before the main expression: version and namespace declarations, global variables, and your own functions. It is what lets an XQuery grow past a one-liner into a maintainable transformation, and it is the piece with no XPath equivalent at all. Every prolog item ends with a semicolon.

xquery version "3.1";

Version declaration — the first thing in the query

Optional in most engines but good practice: it pins the language version and, with an encoding clause, the character encoding. If present it must come before every other prolog item.

Example: xquery version "3.1";

declare namespace p = "URI";

Bind a namespace prefix for the whole query

Declares a prefix you can then use in path steps and constructors. This is the in-query alternative to binding prefixes in the Sandbox's namespace panel, and it travels with the query when you save or share it.

Example: declare namespace atom = "http://www.w3.org/2005/Atom";

declare default element namespace "URI";

Make unprefixed names resolve into a namespace

Sets the namespace applied to unprefixed element names in both path steps and constructors. This is the cleanest fix for the classic 'my query returns nothing' problem on a namespaced document.

Example: declare default element namespace "http://www.w3.org/2005/Atom";

declare variable $x := EXPR;

Global variable available to the whole query

Defines a value once and reuses it everywhere. Add 'external' instead of a value to declare a parameter the caller supplies. Global variables are evaluated lazily, once, no matter how often they are referenced.

Example: declare variable $limit := 10;

declare function local:f($a) {…};

Define a reusable named function

User-defined functions must live in a namespace — local: is the built-in one for functions defined in the main module. Add 'as' type annotations on parameters and the return to catch mistakes early. Recursion is allowed, which is how XQuery handles deep tree transformations.

Example: declare function local:label($b) { string($b/title) };

import module namespace m = "URI" at "…";

Pull in functions and variables from a library module

Splits a large query into library modules. Support depends on the engine and on having a filesystem or repository to resolve the location hint against — in an in-browser environment like this Sandbox, prefer local: functions in the prolog.

Example: import module namespace f = "http://example.com/f" at "f.xqy";

(: comment :)

XQuery comment

XQuery comments are written with the smiley-face delimiters and may be nested. They are allowed anywhere whitespace is, including inside a FLWOR, which makes them the right way to annotate a long query.

Example: (: only books still in stock :)

← Back to the XQuery reference