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. | |||
| 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. | |||
| 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. | |||
The following actions are currently supported:
| Clear | Completely 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. | ||||||||||||
| GetKey | Read XQuery variable values. | |||||||||||
ERR acGetKey(*Object, CSTRING Key, STRING Value, INT Size)
| ||||||||||||
| Init | Compiles 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. | ||||||||||||
| Reset | Clears the information held in an XQuery object. | |||||||||||
| 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
| |||||||||||||||||
| 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 Error Codes
| |||||||||||||||||