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.

  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.

  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.

Actions

The following actions are currently supported:

ClearCompletely clears all XQuery data and resets the object to its initial state.
ERR acClear(*Object)

Use Clear() to remove the resources consumed by the XQuery while still retaining it for future use.

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 converts a valid XQuery expression string into a compiled form that can be executed against an XML document. The resulting compiled expression can be reused multiple times for efficiency and must be freed using FreeResource when no longer needed. They are re-usable between different XML documents and are treated as read-only for thread-safety.

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.

ResetClears the information held in an XQuery object.
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)
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.

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