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.
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.
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.
A rich set of standard functions is provided across multiple categories:
position(), last(), count(), id(), name(), local-name(), namespace-uri(), root(), node-name(), base-uri()concat(), substring(), contains(), starts-with(), ends-with(), string-length(), normalize-space(), upper-case(), lower-case(), translate(), string-join(), encode-for-uri(), escape-html-uri()number(), sum(), floor(), ceiling(), round(), round-half-to-even(), abs(), min(), max(), avg()boolean(), not(), true(), false(), exists(), empty(), lang()distinct-values(), index-of(), insert-before(), remove(), reverse(), subsequence(), unordered(), deep-equal(), zero-or-one(), one-or-more(), exactly-one()matches(), replace(), tokenize(), analyze-string()current-date(), current-time(), current-dateTime(), date and time component extractors, timezone adjustments, duration calculationsdoc(), doc-available(), collection(), unparsed-text(), unparsed-text-lines(), document-uri()QName(), resolve-QName(), prefix-from-QName(), local-name-from-QName(), namespace-uri-from-QName(), namespace-uri-for-prefix(), in-scope-prefixes()resolve-uri(), iri-to-uri()format-date(), format-time(), format-dateTime(), format-integer()error(), trace()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.
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.
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.
The XQuery class consists of the following fields:
Access | Name | Type | Comment |
|---|---|---|---|
| ErrorMsg | STRING | A 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. | |||
| FeatureFlags | INT | Flags indicating the features of a compiled XQuery expression. | |
| Functions | pf::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 Example: For Duplicate function names are not removed. | |||
| MemoryUsage | INT64 | Returns 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. | |||
| Path | STRING | Base 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. | |||
| Result | APTR | 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. | |||
| ResultString | STRING | Returns 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. | |||
| ResultType | INT | Returns the value type of the most recently executed query. | |
If an XQuery expression returns a Result, the type can be retrieved from this field. | |||
| Statement | STRING | XQuery 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. | |||
| Variables | pf::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 Example: For Duplicate variable names are not removed. | |||
The following actions are currently supported:
| Activate | Run 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
| ||||||||||||
| Clear | Clears all XQuery results and returns the object to its pre-compiled state. | |||||||||||
| GetKey | Read XQuery variable values. | |||||||||||
ERR acGetKey(*Object, CSTRING Key, STRING Value, INT Size)
| ||||||||||||
| Init | Compiles 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. | ||||||||||||
| Reset | Synonym for Clear(). | |||||||||||
| SetKey | Set XQuery variable values. | |||||||||||
ERR acSetKey(*Object, CSTRING Key, CSTRING Value)
Use SetKey to store key-value pairs that can be referenced in XQuery expressions using the variable syntax Error Codes
| ||||||||||||
The following methods are currently supported:
| Evaluate | Run an XQuery expression against an XML document. | ||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ERR xq::Evaluate(OBJECTPTR Object, objXML * XML)
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
| |||||||||||||||||
| InspectFunctions | Returns information about compiled XQuery functions. | ||||||||||||||||
ERR xq::InspectFunctions(OBJECTPTR Object, CSTRING Name, XIF ResultFlags, CSTRING * Result)
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
| |||||||||||||||||
| RegisterFunction | Register a custom XQuery function. | ||||||||||||||||
ERR xq::RegisterFunction(OBJECTPTR Object, CSTRING FunctionName, FUNCTION * Callback)
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
| |||||||||||||||||
| Search | For node-based queries, calls a function for each matching node. | ||||||||||||||||
ERR xq::Search(OBJECTPTR Object, objXML * XML, FUNCTION * Callback)
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 The C++ prototype for Callback is Error Codes
| |||||||||||||||||
Result flags for InspectFunctions().
| Name | Description |
|---|---|
| XIF::ALL | Synonym for AST | NAME | PARAMETERS | RETURN_TYPE | USER_DEFINED | SIGNATURE |
| XIF::AST | Include the compiled function body in the inspection result. |
| XIF::NAME | Include function name in the inspection result. |
| XIF::PARAMETERS | Include function parameters in the inspection result. |
| XIF::RETURN_TYPE | Include function return type in the inspection result. |
| XIF::SIGNATURE | Include function signature in the inspection result. |
| XIF::USER_DEFINED | Include user-defined status in the inspection result. |