Kōtuku
  • Gallery
  • API
  • Wiki
  • GitHub
    • Audio
    • Config
    • Core
    • Display
    • Document
    • Font
    • HTTP
    • Network
    • Regex
    • SVG
    • Tiri
    • Vector
    • XML
    • XQuery
    • XRandR
      • Audio
      • MP3
      • Sound
      • File
      • MetaClass
      • Module
      • StorageDevice
      • Task
      • Thread
      • Time
      • Compression
      • CompressedStream
      • Config
      • LZMAStream
      • Script
      • Tiri
      • XML
      • XQuery
      • Controller
      • BlurFX
      • ColourFX
      • CompositeFX
      • ConvolveFX
      • DisplacementFX
      • FilterEffect
      • FloodFX
      • ImageFX
      • LightingFX
      • MergeFX
      • MorphologyFX
      • OffsetFX
      • RemapFX
      • SourceFX
      • TurbulenceFX
      • WaveFunctionFX
      • Scintilla
      • Bitmap
      • Clipboard
      • Display
      • Document
      • Font
      • Image
      • Pointer
      • Surface
      • SVG
      • ClientSocket
      • HTTP
      • NetClient
      • NetLookup
      • NetServer
      • NetSocket
      • Proxy
      • Gradient
      • GradientConic
      • GradientContour
      • GradientDiamond
      • GradientDiffusion
      • GradientDistal
      • GradientGouraud
      • GradientLinear
      • GradientMesh
      • GradientRadial
      • GradientVoronoi
      • Vector
      • VectorClip
      • VectorColour
      • VectorEllipse
      • VectorFilter
      • VectorGradient
      • VectorGroup
      • VectorImage
      • VectorPath
      • VectorPattern
      • VectorPolygon
      • VectorRectangle
      • VectorScene
      • VectorShape
      • VectorSpiral
      • VectorText
      • VectorTransition
      • VectorViewport
      • VectorWave
      • Linux Builds
      • Windows Builds
      • Customising Your Build
      • Kōtuku Objects
      • Kōtuku In Depth
      • Kōtuku Design Patterns
      • Coding With AI
      • Regex Manual
      • XML Comparisons
      • Tiri Reference Manual
      • Config API
      • Defer Syntax
      • GUI API
      • HTTP Server API
      • I/O API
      • JSON API
      • OAuth API
      • Options API
      • Proxy Server API
      • Tempus API
      • URL API
      • VFX API
      • Widgets
      • RIPL Reference Manual
      • Origo
      • Flute / Unit Testing
      • Tuku
      • Embedded Document Format
      • TDL Reference Manual
      • TDL Tools
      • Action Reference Manual
      • System Error Codes

XQuery Class

Provides an interface for XQuery evaluation and execution.

The XQuery class provides comprehensive support for executing XPath 2.0 and XQuery expressions, enabling navigation of XML documents. It operates in conjunction with the XML class to provide a standards-compliant query engine with extensive functionality.

XPath 2.0 Path Expressions

The class supports the full XPath 2.0 specification for navigating XML documents, including all 13 standard axes (child, descendant, descendant-or-self, following, following-sibling, parent, ancestor, ancestor-or-self, preceding, preceding-sibling, self, attribute, and namespace), node tests for element names, wildcards (*), and attribute selectors (@attr), numeric position filters ([1], [2]), comparison operators, and complex boolean expressions in predicates. Both absolute paths (/root/element), relative paths (element/subelement), and recursive descent (//element) are supported.

XQuery Language Support

The class implements core XQuery 1.0 functionality including FLWOR expressions (for, let, where, order by, and return clauses) for advanced querying, sequence operations for constructing, filtering, and manipulating sequences of nodes and values, and a comprehensive type system supporting strings, numbers, booleans, node sets, dates, durations, and QNames.

Informal support for XQuery 2.0 functionality is also included but the feature-set is not yet complete.

Function Library

A rich set of standard functions is provided across multiple categories:

  • Node Functions: position(), last(), count(), id(), name(), local-name(), namespace-uri(), root(), node-name(), base-uri()
  • String Functions: concat(), substring(), contains(), starts-with(), ends-with(), string-length(), normalize-space(), upper-case(), lower-case(), translate(), string-join(), encode-for-uri(), escape-html-uri()
  • Numeric Functions: number(), sum(), floor(), ceiling(), round(), round-half-to-even(), abs(), min(), max(), avg()
  • Boolean Functions: boolean(), not(), true(), false(), exists(), empty(), lang()
  • Sequence Functions: distinct-values(), index-of(), insert-before(), remove(), reverse(), subsequence(), unordered(), deep-equal(), zero-or-one(), one-or-more(), exactly-one()
  • Regular Expressions: matches(), replace(), tokenize(), analyze-string()
  • Date and Time Functions: current-date(), current-time(), current-dateTime(), date and time component extractors, timezone adjustments, duration calculations
  • Document Functions: doc(), doc-available(), collection(), unparsed-text(), unparsed-text-lines(), document-uri()
  • QName Functions: QName(), resolve-QName(), prefix-from-QName(), local-name-from-QName(), namespace-uri-from-QName(), namespace-uri-for-prefix(), in-scope-prefixes()
  • URI Functions: resolve-uri(), iri-to-uri()
  • Formatting Functions: format-date(), format-time(), format-dateTime(), format-integer()
  • Utility Functions: error(), trace()

Expression Compilation

XPath and XQuery expressions are compiled into an optimised internal representation for efficient reuse. Expressions can be run in their own thread, with the result available in Result and ResultString on completion, but the targeted XML object will be locked for the duration of the query.

Evaluation Modes

There are two distinct methods for query evaluation. Value evaluation returns typed results (XPathValue) that can represent node sets, strings, numbers, booleans, dates, or sequences. Node iteration invokes a callback function for each matching node, enabling streaming processing of large result sets.

Usage Patterns

Compiling and evaluating queries:

objXQuery::create query { statement="/bookstore/book[@price < 10]/title" };
if (query.ok()) {
   XPathValue *result;
   if (!query->evaluate(xml)) {
      std::string_view str;
      query->getResultString(str);
      log.msg("Got: %s", str.data());
   }
}

Node iteration with callbacks:

objXQuery::create query { statement="//chapter[@status='draft']" };
if (query.ok()) {
   auto callback = C_FUNCTION(process_node);
   query->search(xml, &callback);
}

Extensions

The module includes several Kotuku-specific extensions beyond the standard specification. Content matching with the [=...] syntax allows matching on encapsulated content, e.g., /menu[=contentmatch]. Backslash (\) can be used as an escape character in attribute strings.

Structure

The XQuery class consists of the following fields:

Access
NameTypeComment
 ErrorMsgSTRINGA readable description of the last parse or execution error.

This field may provide a textual description of the last parse or execution error that occurred.

 FeatureFlagsINTFlags indicating the features of a compiled XQuery expression.
 Functionskt::vector<std::string>Returns an allocated list of all declared XQuery functions.

Provides a list of all XQuery functions that have been defined by the user or during evaluation of the XQuery expression (via the declare keyword).

Example: For declare function math:cube($x) { } the name math:cube would appear in the list.

Duplicate function names are not removed.

 MemoryUsageINT64The total amount of memory allocated by the last compilation or evaluation.

If the XQuery module has been compiled with ANALYSE_MEMORY_USAGE defined, this field will contain the total amount of memory (in bytes) allocated during the last compilation or evaluation of the XQuery object.

 PathSTRINGBase path for resolving relative references.

Set the Path field to define the base-uri for an XQuery expression. If left unset, the path will be computed through automated means on-the-fly, which relies on the working directory or XML document path.

 ResolveVariableFUNCTIONCallback function for resolving unknown variables.

This callback is invoked when an XQuery expression refers to a variable that has not been declared in the XQuery expression or XQuery module. Variable resolution precedence is:

  • Evaluator-local bindings
  • SetKey() string variables
  • Declared/internal XQuery variables
  • This callback for otherwise unresolved names

The C++ prototype is ERR ResolveVariable(objXQuery *Query, std::string_view Name, XPathValue *Result, APTR Meta). Script callbacks are not supported.

Return ERR::Okay when the variable is recognised and Result has been populated, ERR::Search when the name is unknown, or another error code to abort evaluation.

 Resultstruct XPathValue *Returns the results of the most recently executed query.

Following the successful execution of an XQuery expression, the results can be retrieved as an XPathValue object through this field.

 ResultStringSTRINGReturns the results of the most recently executed query as a string.

Following the successful execution of an XQuery expression, the results can be retrieved as a string through this field. The string representation is generated from the Result field, which holds the raw evaluation output.

Note that if the result is empty, the returned string will also be empty (i.e. is not considered an error). The string is managed internally and does not require manual deallocation.

The string result becomes invalid if the XQuery object is modified, re-executed or destroyed.

 ResultTypeINTReturns the value type of the most recently executed query.

If an XQuery expression returns a Result, the type can be retrieved from this field.

 StatementSTRINGXQuery statements are specified here.

Set the Statement field with an XPath or XQuery expression for compilation.

If this field is set after initialisation then Clear() will be applied to the object first. The expression will be compiled on the next execution attempt.

If the statement is an XQuery expression with base-uri references, the Path field should be set to establish the base path for relative references.

 Variableskt::vector<std::string>Returns an allocated list of all defined XQuery variables.

Provides a list of all XQuery variables that have been defined using the SetKey() action, or during evaluation of the XQuery expression (via the declare keyword).

Example: For declare variable $math:pi := 3.14159; the variable name math:pi would appear in the list.

Duplicate variable names are not removed.

Actions

The following actions are currently supported:

ActivateRun an XQuery expression.
ERR acActivate(*Object)

Use Activate to run a compiled XQuery expression without an XML document reference. The result of the evaluation is returned in the Result field as XPathValue, which can represent various types of data including node sets, strings, numbers, or booleans. On error, the ErrorMsg field will contain a descriptive message.

Use Evaluate() or Search() for expressions expecting an XML document context.

Error Codes
OkayOperation successful.
SyntaxInvalid syntax detected
ClearClears all XQuery results and returns the object to its pre-compiled state.
ERR acClear(*Object)

Use Clear() to remove the resources consumed by the XQuery and reset its state. The Statement and Path field values are retained, allowing the object to be seamlessly re-activated at any time.

GetKeyRead XQuery variable values.
ERR acGetKey(*Object, std::string_view Key, std::string &Value)
ParameterDescription
KeyThe name of a key value.
ValuePointer to a buffer space large enough to hold the retrieved value.
InitCompiles the XQuery statement.
ERR InitObject(*Object)

Initialisation will compile the XQuery Statement string into a compiled form that can be executed.

If parsing fails, the object will not be initialised and an error message will be defined in the ErrorMsg field.

Note: This function can hang temporarily if the expression references network URIs. Consider calling it from a separate thread to avoid blocking in such cases.

ResetSynonym for Clear().
SetKeySet XQuery variable values.
ERR acSetKey(*Object, std::string_view Key, std::string_view Value)
ParameterDescription
KeyThe name of the target key.
ValueThe string value to associate with Key.

Use SetKey to store key-value pairs that can be referenced in XQuery expressions using the variable syntax $variableName.

Error Codes
OkayOperation successful.
NullArgsThe Key parameter was not specified.

Methods

The following methods are currently supported:

EvaluateRun an XQuery expression against an XML document.
ERR xq::Evaluate(OBJECTPTR Object, objXML * XML, INT Index, XEF Flags)
ParameterDescription
XMLTargeted XML document to query. Can be NULL for XQuery expressions that do not require a context.
IndexOptional tag index that establishes the initial context for the query.
FlagsOptional flags.

Use Evaluate to run a compiled XQuery expression against an XML document. The result of the evaluation is returned in the Result field as XPathValue, which can represent various types of data including node sets, strings, numbers, or booleans.

Error Codes
OkayOperation successful.
NotFoundA search routine in this function failed
AllocMemoryFailed to create a new memory block
NotInitialisedThe resource has not been initialised
NullArgsFunction call missing argument value(s)
InspectFunctionsReturns information about compiled XQuery functions.
ERR xq::InspectFunctions(OBJECTPTR Object, STRVIEW Name, XIF ResultFlags, STRING * Result)
ParameterDescription
NameThe name of the function or functions to inspect (supports wildcards).
ResultFlagsBitmask controlling the returned information.
ResultReceives a serialised XML document describing the function(s).

Use InspectFunctions to retrieve metadata about user-defined or standard XQuery functions available in the compiled XQuery object. The function name can include wildcards to match multiple functions.

The ResultFlags parameter controls which pieces of information are included in the output XML document. If no flags are specified, all available information is returned.

The structure of the returned XML document is as follows, with each matching function returned in series:

<function>
  <name>function-name</name>
  <parameters>
    <parameter>
      <name>param1</name>
      <type>type1</type>
    </parameter>
    ...
  </parameters>
  <returnType>type</returnType>
  <userDefined>true|false</userDefined>
  <signature>function-signature</signature>
  <ast>... serialized function body AST ...</ast>
</function>
Error Codes
OkayOperation successful.
SearchA search routine in this function failed
NullArgsFunction call missing argument value(s)
RegisterFunctionRegister a custom XQuery function.
ERR xq::RegisterFunction(OBJECTPTR Object, STRVIEW FunctionName, FUNCTION Callback)
ParameterDescription
FunctionNameThe name of the function to register (e.g., "custom-function").
CallbackThe callback function to register for FunctionName.

Use RegisterFunction to define a custom function that can be invoked within XQuery expressions. The function will be associated with the specified name and can be called like any standard XQuery function.

The C++ function prototype is ERR (*XQuery, std::string_view FunctionName, const std::vector<XPathValue> &Args, XPathValue &Result, APTR Meta))

Script callbacks are not currently supported.

Error Codes
OkayOperation successful.
NoSupportThe provided callback is not a C function reference.
NullArgsFunction call missing argument value(s)
SearchFor node-based queries, calls a function for each matching node.
ERR xq::Search(OBJECTPTR Object, objXML * XML, FUNCTION Callback, INT Index, XEF Flags)
ParameterDescription
XMLTarget XML document to search.
CallbackOptional callback function to invoke for each matching node.
IndexOptional tag index that establishes the initial context for the query.
FlagsOptional flags.

Use the Search method to scan an XML document for tags or attributes that match a compiled XQuery expression. For every matching node, a user-defined callback function is invoked, allowing custom processing of each result.

If no callback is provided, the search stops after the first match and the XML object's cursor markers will reflect the position of the node.

Note that valid function execution can return ERR:Search if zero matches are found.

The C++ prototype for Callback is ERR Function(*XML, int TagID, CSTRING Attrib, APTR Meta). For Tiri, use function(XML, TagID, Attrib)

Error Codes
OkayAt least one matching node was found and processed.
TerminateThe callback function requested termination of the search.
SearchNo matching node was found.
NotFoundThe specified Index does not correspond to a valid XML tag.
SyntaxThe provided query expression has syntax errors.
NullArgsAt least one required parameter was not provided.
XQuery class documentation © Paul Manias © 2025-2026

XEF Type

Options for XQuery evaluation flags.

NameDescription
XEF::LIMIT_SCOPEFor tag specific queries, limit the scope to the specified element.
XQuery module documentation © Paul Manias © 2025-2026

XIF Type

Result flags for InspectFunctions().

NameDescription
XIF::ALLSynonym for AST | NAME | PARAMETERS | RETURN_TYPE | USER_DEFINED | SIGNATURE
XIF::ASTInclude the compiled function body in the inspection result.
XIF::NAMEInclude function name in the inspection result.
XIF::PARAMETERSInclude function parameters in the inspection result.
XIF::RETURN_TYPEInclude function return type in the inspection result.
XIF::SIGNATUREInclude function signature in the inspection result.
XIF::USER_DEFINEDInclude user-defined status in the inspection result.
XQuery module documentation © Paul Manias © 2025-2026

XPVT Type

Type descriptors for XPathValue

NameDescription
XPVT::Array
XPVT::Boolean
XPVT::Date
XPVT::DateTime
XPVT::Map
XPVT::NodeSet
XPVT::Number
XPVT::String
XPVT::Time
XQuery module documentation © Paul Manias © 2025-2026

XQF Type

Flags indicating the features of a compiled XQuery expression.

NameDescription
XQF::BASE_URI_DECLAREDStatic base URI declared.
XQF::BOUNDARY_PRESERVEBoundary-space preserve mode.
XQF::CONSTRUCTION_PRESERVEConstruction preserve mode.
XQF::DEFAULT_COLLATION_DECLAREDDefault collation declared.
XQF::DEFAULT_ELEMENT_NSDefault element namespace declared.
XQF::DEFAULT_FUNCTION_NSDefault function namespace declared.
XQF::HAS_PROLOGThe XQuery declares a prolog.
XQF::HAS_WILDCARD_TESTSWildcard name tests present.
XQF::LIBRARY_MODULEProlog declares a module namespace (library module).
XQF::MODULE_IMPORTSOne or more module imports are declared.
XQF::ORDERING_UNORDEREDOrdering mode is unordered.
XQF::XPATHThe expression is an XPath location string.
XQuery module documentation © Paul Manias © 2025-2026