Parasol Framework
  • Gallery
  • API
  • Wiki
  • GitHub
    • Audio
    • Core
    • Display
    • Fluid
    • Font
    • Network
    • Regex
    • Vector
    • XML
    • XQuery
    • Audio
    • Sound
    • File
    • MetaClass
    • Module
    • StorageDevice
    • Task
    • Thread
    • Time
    • Compression
    • CompressedStream
    • Config
    • Script
    • XML
    • XQuery
    • Controller
    • BlurFX
    • ColourFX
    • CompositeFX
    • ConvolveFX
    • DisplacementFX
    • FilterEffect
    • FloodFX
    • ImageFX
    • LightingFX
    • MergeFX
    • MorphologyFX
    • OffsetFX
    • RemapFX
    • SourceFX
    • TurbulenceFX
    • WaveFunctionFX
    • Scintilla
    • ScintillaSearch
    • Bitmap
    • Clipboard
    • Display
    • Document
    • Font
    • Picture
    • Pointer
    • Surface
    • SVG
    • ClientSocket
    • HTTP
    • NetClient
    • NetLookup
    • NetSocket
    • Proxy
    • Vector
    • VectorClip
    • VectorColour
    • VectorEllipse
    • VectorFilter
    • VectorGradient
    • VectorGroup
    • VectorImage
    • VectorPath
    • VectorPattern
    • VectorPolygon
    • VectorRectangle
    • VectorScene
    • VectorShape
    • VectorSpiral
    • VectorText
    • VectorTransition
    • VectorViewport
    • VectorWave

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) IS ERR::Okay) {
      log.msg("Got: %s", query->get(FID_ResultString));
   }
}


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 Parasol-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.
  Functionspf::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.

  MemoryUsageINT64Returns the 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 return 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.

  ResultAPTRReturns 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 data is processed through this field.

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.

  Variablespf::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, CSTRING Key, STRING Value, INT Size)
ParameterDescription
KeyThe name of a key value.
ValuePointer to a buffer space large enough to hold the retrieved value.
SizeIndicates the byte size of the Buffer.
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, CSTRING Key, CSTRING 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)
ParameterDescription
XMLTargeted XML document to query. Can be NULL for XQuery expressions that do not require a context.

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.
AllocMemoryAllocMemory() failed to create a new memory block.
NullArgsFunction call missing argument value(s)
InspectFunctionsReturns information about compiled XQuery functions.
ERR xq::InspectFunctions(OBJECTPTR Object, CSTRING Name, XIF ResultFlags, CSTRING * 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.
NullArgsFunction call missing argument value(s)
RegisterFunctionRegister a custom XQuery function.
ERR xq::RegisterFunction(OBJECTPTR Object, CSTRING 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.

Error Codes
OkayOperation successful.
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)
ParameterDescription
XMLTarget XML document to search.
CallbackOptional callback function to invoke for each matching node.

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 Fluid, 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.
SyntaxThe provided query expression has syntax errors.
NullArgsAt least one required parameter was not provided.
XQuery class documentation © Paul Manias © 2025

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