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

XML Class

Parses, queries and updates XML document structures.

The XML class creates and maintains parsed XML data as a hierarchy of XTag structures. It accepts both strictly well-formed XML and the module's default relaxed parsing mode, depending on the Flags supplied by the caller. Parsed documents can be queried with XPath/XQuery expressions, modified with XML methods and validated against an XML Schema loaded with LoadSchema().

XML data can be loaded from a file path, from an in-memory XML statement or from another object that supports the Read action. Set Path to load from the file system, Statement to parse an XML string, or Source to read from another object. When Path or Statement is changed after initialisation, the object clears the previous document and parses the new source.

Parsed content is available through Tags. Each XTag stores the element name, attributes, child tags, content nodes, line number and namespace ID. C++ callers can traverse the hierarchy directly through kt::vector<XTag>; Tiri callers should cache Tags only while the XML object remains unchanged because reading the field copies the structure.

Use the XML object's methods when changing the tree so that modification timestamps and derived state remain consistent. Direct read access to XTag is appropriate for traversal and high-volume inspection.

Not supported: DTD validation is not implemented. The parser records DOCTYPE declarations and selected entity, notation and identifier data, but it does not load or validate external DTDs. Use XML Schema (XSD) validation instead.

Structure

The XML class consists of the following fields:

Access
NameTypeComment
 DocTypeSTRINGRoot element name from a parsed DOCTYPE declaration.
 ErrorMsgSTRINGA textual description of the last parse error.

This field may provide a textual description of the last parse error that occurred, in conjunction with the most recently received error code. Issues parsing malformed XPath expressions may also be reported here.

 FlagsXMFControls XML parsing behaviour and processing options.
NameDescription
XMF::HAS_SCHEMAAutomatically defined when a schema has been loaded into the XML object.
XMF::INCLUDE_COMMENTSBy default, comments are stripped when parsing XML input unless this flag is specified.
XMF::INCLUDE_SIBLINGSInclude siblings when building an XML string (GetXMLString() only)
XMF::INCLUDE_WHITESPACEBy default the XML parser will skip content between tags when they contain pure whitespace. Setting this flag will retain all whitespace.
XMF::INDENTIndent the output of serialised XML to improve readability.
XMF::LOCK_REMOVEPrevents removal of tags from the XML tree. This specifically affects the RemoveTag and RemoveXPath methods.
XMF::LOG_ALLPrint extra log messages.
XMF::NAMESPACE_AWAREEnable namespace processing during parsing.
XMF::NEWCreates an empty XML object on initialisation - if the Path field has been set, the source file will not be loaded.
XMF::NO_ESCAPETurns off escape code conversion.
XMF::OMIT_TAGSPrevents tags from being output when the XML is serialised (output content only).
XMF::PARSE_ENTITYEnables parsing of DOCTYPE entities.
XMF::PARSE_HTMLAutomatically parse HTML escape codes.
XMF::READABLEIndent the output of serialised XML to improve readability.
XMF::READ_ONLYEdits to the document are not permitted.
XMF::STANDALONEAutomatically defined when the XML declaration specifies standalone="yes".
XMF::STRIP_CDATADo not serialise CDATA sections. Note that this option is used as a parameter, not an object flag.
XMF::STRIP_CONTENTStrip all content from incoming XML data.
XMF::STRIP_HEADERSXML headers found in the source data will not be included in the parsed results.
XMF::WELL_FORMEDBy default, the XML class will accept badly structured XML data. This flag requires that XML statements must be well-formed (tags must balance) or an ERR::BadData error will be returned during processing.
 ModifiedINTA timestamp of when the XML data was last modified.

The Modified field provides an artificial timestamp value of when the XML data was last modified (e.g. by a tag insert or update). Storing the current Modified value and making comparisons later makes it easy to determine that a change has been made. A rough idea of the total number of change requests can also be calculated by subtracting out the difference.

 PathSTRINGSet this field if the XML document originates from a file source.

XML documents can be loaded from the file system by specifying a file path in this field. If set post-initialisation, all currently loaded data will be cleared and the file will be parsed automatically.

The XML class supports LoadFile(), so an XML file can be pre-cached by the program if it is frequently used during a program's life cycle.

In the case where a Statement has been defined, setting the Path with a folder reference may be necessary to establish the base path for relative references in XQuery statements (e.g. for importing XQuery modules).

 PublicIDSTRINGPublic identifier from a parsed DOCTYPE declaration.
 SourceOBJECTPTRSet this field if the XML data is to be sourced from another object.

An XML document can be loaded from another object by referencing it here, on the condition that the object's class supports the Read action.

If set post-initialisation, all currently loaded data will be cleared and the source object will be parsed automatically.

 StatementSTRINGXML data is processed through this field.

Set the Statement field to parse an XML formatted data string through the object. If this field is set after initialisation then the XML object will clear any existing data first.

Be aware that setting this field with an invalid statement will result in an empty XML object.

Reading the Statement field returns a serialised string of XML data. By default, all tags are included in the statement. The string result is an allocation that must be freed by the caller.

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.

 SystemIDSTRINGSystem identifier from a parsed DOCTYPE declaration.
 TagsXTag[]Provides direct access to the XML document structure.

The Tags field exposes the complete XML document structure as a hierarchical array of XTag structures. This field becomes available after successful XML parsing and provides the primary interface for reading XML content programmatically.

Each XTag will have at least one attribute set in the Attribs array. The first attribute will either reflect the tag name or a content string if the Name is undefined. The Children array provides access to all child elements.

Direct read access to the Tags hierarchy is safe and efficient for traversing the document structure. However, modifications should be performed using the XML object's methods (InsertXML(), SetAttrib(), RemoveTag(), etc.) to maintain internal consistency and trigger appropriate cache invalidation.

NOTE: Tiri will copy this field on read, caching the value is therefore recommended.

Actions

The following actions are currently supported:

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

The Clear action removes parsed XML content, namespace base URI mappings, DOCTYPE information, entity data, notation data and parser status. The object remains usable and can receive new XML data afterwards.

Error Codes
OkayOperation successful.
DataFeedProcesses and integrates external XML data into the object's document structure.
ERR acDataFeed(*Object, OBJECTID Object, DATA Datatype, std::span<const int8_t> Buffer)
ParameterDescription
ObjectMust refer to the unique ID of the object that you represent. If you do not represent an object, set this parameter to the current task ID.
DatatypeThe type of data being sent.
BufferThe data being sent to the target object.

DataFeed accepts XML or text data and parses it into the object's tag hierarchy. If the object has no existing tags, the parsed data becomes the document structure. If tags already exist, the new data is parsed into a temporary hierarchy and appended to the root-level tag list.

The action is rejected when XMF::READ_ONLY is enabled. Parse failures are returned to the caller; when appending to an existing document, the existing tag hierarchy is left unchanged if the new data cannot be parsed.

Example:

local xml = obj.new('xml') local err = xml.acDataFeed(nil, DATA_XML, 'First element')
Error Codes
OkayOperation successful.
FailedGeneral failure
InvalidDataThere is an error in the provided data
ReadOnlyA delete or write operation failed due to read-only status
SyntaxInvalid syntax detected
NullArgsFunction call missing argument value(s)
UnbalancedXMLThe XML tags do not balance
ResetClears the information held in an XML object.
SaveToObjectSaves XML data to a storage object (e.g. File), optionally using another format encoder.
ERR acSaveToObject(*Object, OBJECTID Dest, CLASSID ClassID)
ParameterDescription
DestRefers to an object that will receive the encoded data.
ClassIDCan refer to a derived class that should be used when encoding the data.

Set ClassID to NIL or XML to write XML. Another XML-derived class ID delegates the action to that class's distinct SaveToObject implementation, allowing XML-backed data to be exported in formats such as JSON.

SetKeySets attributes and content in the XML tree using XPaths.
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 add tag attributes and content using XPaths. The XPath is specified in the Key parameter and the data is specified in the Value parameter. If the XPath resolves to an attribute, the attribute is updated or created on the matched tag. If the XPath resolves to an element, the element's first content node is updated or a new content node is created.

It is not possible to add new tags using this action - it is only possible to update existing tags.

Please note that making changes to the XML tree will render all previously obtained tag pointers and indexes invalid.

Error Codes
OkayOperation successful.
TerminateTermination requested
SearchFailed to find the tag referenced by the XPath.
NewObjectNewObject() failed to produce a new object
ReadOnlyChanges to the XML structure are not permitted.
NullArgsFunction call missing argument value(s)
SanityCheckFailedA sanity check has failed

Methods

The following methods are currently supported:

EvaluateRun an XQuery expression against the XML data.
ERR xml::Evaluate(OBJECTPTR Object, STRVIEW Statement, STRING * Result)
ParameterDescription
StatementAn XQuery expression to evaluate.
ResultThe evaluation result is returned here.

The Evaluate method allows the execution of XPath 2.0+ and XQuery 1.0+ expressions against the data contained within the XML object. This is a lazy execution method that compiles and evaluates the provided expression in a single step, returning the result as a string. For more complex scenarios or repeated evaluations, consider using the Compile and Evaluate functions in the XPath module.

Error Codes
OkayOperation successful.
FieldNotSetA required field value is undefined
NewObjectNewObject() failed to produce a new object
NullArgsFunction call missing argument value(s)
FilterFilters the XML data structure to retain only a specific tag and its descendants.
ERR xml::Filter(OBJECTPTR Object, STRVIEW XPath)
ParameterDescription
XPathXPath/XQuery expression that identifies the target tag to retain.

The Filter method provides a mechanism for reducing large XML documents to a specific subtree, permanently removing all content that exists outside the targeted element and its children. This operation is particularly valuable for performance optimisation when working with large documents where only a specific section is relevant.

The filtering process locates the first element matched by the supplied XPath/XQuery expression. The XML object is then replaced by a new root-level structure containing that tag and its descendants. Sibling tags, parent elements and unrelated branches are discarded.

Error Codes
OkayThe XML structure now contains only the first matched subtree.
TerminateTermination requested
SearchNo matching tag could be found for the specified XPath expression.
NewObjectNewObject() failed to produce a new object
NullArgsThe XPath parameter was empty.
GetAttribRetrieves the value of a specific XML attribute from a tagged element.
ERR xml::GetAttrib(OBJECTPTR Object, INT Index, STRVIEW Attrib, STRING * Value)
ParameterDescription
IndexThe unique identifier of the XML tag to search.
AttribThe name of the attribute to retrieve. If empty, the element's tag name is returned instead.
ValueReceives the attribute value. It is cleared if the specified attribute does not exist.

The GetAttrib method provides efficient access to individual attribute values within XML elements. Given a tag identifier and attribute name, the method performs a case-insensitive search through the element's attribute collection and returns the corresponding value.

When a specific attribute name is provided, the method searches through all attributes of the target tag. The search is case-insensitive to accommodate XML documents with varying capitalisation conventions.

When the attribute name is empty, the method returns the tag name itself, providing convenient access to element names without requiring separate API calls.

For applications requiring frequent attribute access or high-performance scenarios, C++ developers should consider direct access to the XMLAttrib structure array. This bypasses the method call overhead and provides immediate access to all attributes simultaneously.

The method performs a linear search through the attribute collection, so performance scales with the number of attributes per element. For elements with many attributes, caching frequently accessed values may improve performance.

Error Codes
OkayThe attribute was successfully found and its value returned.
NotFoundEither the specified tag Index does not exist, or the named attribute was not found within the tag.
NullArgsRequired arguments were not specified correctly.
GetContentExtracts the immediate text content of an XML element, excluding nested tags.
ERR xml::GetContent(OBJECTPTR Object, INT Index, STRING * Buffer)
ParameterDescription
IndexThe unique identifier of the XML element from which to extract content.
BufferReceives the extracted content string.

The GetContent method extracts only the immediate content-node children of the specified element. Text contained inside nested elements is not included.

Consider the following XML structure:

<body>
  Hello
  <bold>emphasis</bold>
  world!
</body>

The GetContent method would extract Hello world! and deliberately exclude emphasis since it is contained within the nested <bold> element.

For scenarios requiring serialised XML rather than immediate text content, use Serialise(). To inspect nested text content, traverse the child XTag hierarchy directly.

It is recommended that C++ programs bypass this method and access the XMLAttrib structure directly.

Error Codes
OkayThe content string was successfully extracted and copied to the buffer.
NotFoundThe tag identified by Index does not exist in the XML structure.
NullArgsEither the Buffer parameter was NULL or other required arguments were missing.
GetEntityRetrieves the value of a parsed entity declaration.
ERR xml::GetEntity(OBJECTPTR Object, STRVIEW Name, STRING * Value)
ParameterDescription
NameThe name of the entity to retrieve. This must correspond to a parsed entity declaration.
ValueReceives the resolved entity value on success.

This method returns the expanded value associated with a general entity parsed from the document's DOCTYPE declaration. Entity names are case-sensitive and must match exactly as declared.

Error Codes
OkayThe entity was found and its value returned.
SearchNo matching entity could be found for the specified name.
NullArgsEither the Name was empty or Value parameter was NULL.
GetNamespaceURIRetrieve the namespace URI for a given namespace UID.
ERR xml::GetNamespaceURI(OBJECTPTR Object, UINT NamespaceID, STRING * Result)
ParameterDescription
NamespaceIDThe UID of the namespace.
ResultReceives the namespace URI.

This method retrieves the original namespace URI string for a given namespace UID.

Error Codes
OkayThe namespace URI was successfully retrieved.
SearchNo namespace found for the specified UID.
NullArgsRequired arguments were not specified correctly.
GetNotationRetrieves information about a parsed notation declaration.
ERR xml::GetNotation(OBJECTPTR Object, STRVIEW Name, STRING * Value)
ParameterDescription
NameThe notation name to look up.
ValueReceives the notation descriptor on success.

Returns the system or public identifier captured for a notation declaration inside the document type definition. If both public and system identifiers were provided they are returned as a single string separated by a single space.

Error Codes
OkayThe notation was found and its descriptor returned.
SearchNo matching notation could be found for the specified name.
NullArgsEither the Name was empty or Value parameter was NULL.
GetTagReturns a pointer to the XTag structure for a given tag index.
ERR xml::GetTag(OBJECTPTR Object, INT Index, struct XTag ** Result)
ParameterDescription
IndexThe index of the tag that is being retrieved.
ResultThe XTag is returned in this parameter.

This method will return the XTag structure for a given tag Index. The Index is checked to ensure it is valid prior to retrieval, and an ERR::NotFound error will be returned if it is invalid.

Error Codes
OkayOperation successful.
NotFoundThe Index is not recognised.
NullArgsFunction call missing argument value(s)
InsertContentInserts text content into the XML document structure at specified positions.
ERR xml::InsertContent(OBJECTPTR Object, INT Index, XMI Where, STRVIEW Content, INT * Result)
ParameterDescription
IndexThe unique identifier of the target XML element that will serve as the reference point for insertion.
WhereSpecifies the insertion position relative to the target element. Use PREV or NEXT for sibling insertion, or CHILD for child content insertion.
ContentThe text content to insert. Special XML characters will be automatically escaped.
ResultPointer to an integer that will receive the unique identifier of the newly created content node.

The InsertContent method will insert content strings into any position within the XML tree. A content string must be provided in the Content parameter and the target insertion point is specified in the Index parameter. An insertion point relative to the target index must be specified in the Where parameter. The new tags can be inserted as a child of the target by using a Where value of XMI::CHILD. To insert behind or after the target, use XMI::PREV or XMI::NEXT.

To modify existing content, call SetAttrib() instead.

Error Codes
OkayThe content was successfully inserted and a new content node was created.
NotFoundThe target Index does not correspond to a valid XML element.
ArgsThe Where parameter specifies an invalid insertion position.
ReadOnlyThe XML object is in read-only mode and cannot be modified.
NullArgsRequired parameters were NULL or not properly specified.
InsertXMLParse an XML string and insert it in the XML tree.
ERR xml::InsertXML(OBJECTPTR Object, INT Index, XMI Where, STRVIEW XML, INT * Result)
ParameterDescription
IndexThe new data will target the tag specified here.
WhereUse PREV or NEXT to insert behind or ahead of the target tag. Use CHILD or CHILD_END for a child insert.
XMLAn XML statement to parse.
ResultThe resulting tag index.

The InsertXML() method is used to translate and insert a new set of XML tags into any position within the XML tree. A standard XML statement must be provided in the XML parameter and the target insertion point is specified in the Index parameter. An insertion point relative to the target index must be specified in the Where parameter. The new tags can be inserted as a child of the target by using a Where value of XMI::CHILD. Use XMI::CHILD_END to insert at the end of the child list. To insert behind or after the target, use XMI::PREV or XMI::NEXT.

Error Codes
OkayThe statement was added successfully.
FailedGeneral failure
InvalidDataThere is an error in the provided data
NotFoundThe target Index does not correspond to a valid XML element.
ArgsThe Where parameter specifies an invalid insertion position.
NoDataThe provided XML statement parsed to an empty result.
ReadOnlyChanges to the XML data are not permitted.
SyntaxInvalid syntax detected
NullArgsRequired parameters were NULL or not properly specified.
UnbalancedXMLThe XML tags do not balance
InsertXPathInserts an XML statement in an XML tree.
ERR xml::InsertXPath(OBJECTPTR Object, STRVIEW XPath, XMI Where, STRVIEW XML, INT * Result)
ParameterDescription
XPathAn XPath string that refers to the target insertion point.
WhereUse PREV or NEXT to insert behind or ahead of the target tag. Use CHILD for a child insert.
XMLXML statement to parse and insert.
ResultThe index of the new tag is returned here.

The InsertXPath method is used to translate and insert a new set of XML tags into any position within the XML tree. A standard XML statement must be provided in the XML parameter and the target insertion point is referenced as a valid XPath location string. An insertion point relative to the XPath target must be specified in the Where parameter. The new tags can be inserted as a child of the target by using a Where value of XMI::CHILD or XMI::CHILD_END. To insert behind or after the target, use XMI::PREV or XMI::NEXT.

Error Codes
OkayThe XML statement was successfully inserted at the specified XPath location.
TerminateTermination requested
FailedGeneral failure
InvalidDataThere is an error in the provided data
NotFoundThe target resolved by XPath could not be used as an insertion point.
SearchThe XPath could not be resolved to a valid location.
ArgsThe Where parameter specifies an invalid insertion position.
NoDataThe provided XML statement parsed to an empty result.
NewObjectNewObject() failed to produce a new object
ReadOnlyThe XML object is in read-only mode and cannot be modified.
SyntaxInvalid syntax detected
NullArgsRequired parameters were NULL or not properly specified.
UnbalancedXMLThe XML tags do not balance
LoadSchemaLoad an XML Schema definition to enable schema-aware validation.
ERR xml::LoadSchema(OBJECTPTR Object, STRVIEW Path)
ParameterDescription
PathFile system path to the XML Schema (XSD) document.

This method parses an XML Schema document and attaches its schema context to the current XML object. Once loaded, schema metadata is available for validation and XQuery evaluation routines that utilise schema-aware behaviour.

Error Codes
OkaySchema was successfully loaded and parsed.
InvalidDataThe schema document did not contain a usable root element.
NoDataThe schema document did not contain any parsable definitions.
CreateObjectThe file in Path could not be processed as XML content.
NullArgsThe Path argument was not provided.
MoveTagsMove an XML tag group to a new position in the XML tree.
ERR xml::MoveTags(OBJECTPTR Object, INT Index, INT Total, INT DestIndex, XMI Where)
ParameterDescription
IndexIndex of the source tag to be moved.
TotalThe total number of sibling tags, including the targeted tag, to move from the source index. Minimum value of 1.
DestIndexThe destination tag index.
WhereUse PREV or NEXT to insert behind or ahead of the target tag. Use CHILD or CHILD_END for a child insert.

This method is used to move XML tags within the XML tree structure. It supports the movement of single and groups of tags from one index to another. The client must supply the index of the tag that will be moved and the index of the target tag. All child tags of the source will be included in the move.

An insertion point relative to the target index must be specified in the Where parameter. The source tag can be inserted as a child of the destination by using XMI::CHILD or XMI::CHILD_END. To insert behind or after the target, use XMI::PREV or XMI::NEXT.

Error Codes
OkayTags were moved successfully.
NotFoundEither the source or destination tag index does not exist.
ArgsInvalid parameter values were provided.
ReadOnlyThe XML object is in read-only mode and cannot be modified.
NullArgsRequired parameters were NULL or not properly specified.
SanityCheckFailedAn internal consistency check failed during the move operation.
RegisterNamespaceRegister a namespace URI and return its UID.
ERR xml::RegisterNamespace(OBJECTPTR Object, STRVIEW URI, UINT * Result)
ParameterDescription
URIThe namespace URI to register. Must not be empty.
ResultPointer to an integer that will receive the UID for the namespace URI.

This method registers a namespace URI and returns a UID that can be used to identify the namespace efficiently throughout the XML document.

Error Codes
OkayThe namespace was successfully registered.
ArgsThe URI could not be registered.
NullArgsRequired arguments were not specified correctly.
RemoveTagRemoves tag(s) from the XML structure.
ERR xml::RemoveTag(OBJECTPTR Object, INT Index, INT Total)
ParameterDescription
IndexReference to the tag that will be removed.
TotalThe total number of sibling tags to delete, including the indicated tag. A value of one or less removes only the indicated tag and its children. The requested range should stay within the available sibling sequence.

The RemoveTag method is used to remove one or more tags from an XML structure. Child tags will automatically be discarded as a consequence of using this method, in order to maintain a valid XML structure.

This method can delete multiple sibling tags when the Total parameter is greater than 1. Each selected tag and its children are removed. The requested range should stay within the available sibling sequence.

Note: Removing tags will destabilise all cached address pointers that have been acquired from the XML object.

Error Codes
OkayThe tag(s) were successfully removed.
NotFoundThe specified tag Index does not exist in the XML structure.
ReadOnlyThe XML object is in read-only mode and cannot be modified.
NullArgsRequired parameters were NULL or not properly specified.
RemoveXPathRemoves tag(s) from the XML structure using an XPath lookup.
ERR xml::RemoveXPath(OBJECTPTR Object, STRVIEW XPath, INT Limit)
ParameterDescription
XPathAn XML path string.
LimitThe maximum number of matching tags to delete. A value of one or zero removes only the indicated tag and its children. A value of -1 removes all matching tags.

The RemoveXPath method is used to remove one or more tags from an XML structure. Child tags will automatically be discarded as a consequence of using this method, in order to maintain a valid XML structure.

Individual tag attributes can also be removed if an attribute is referenced at the end of the XPath.

The removal routine is repeated until no further match is found or the Limit is reached. No-match completion is reported as ERR::Okay.

This method is volatile and will destabilise any cached address pointers that have been acquired from the XML object.

Error Codes
OkayThe matching tag(s) or attribute(s) were successfully removed.
TerminateTermination requested
NoDataThe XML document contains no data to process.
ReadOnlyThe XML object is in read-only mode and cannot be modified.
NullArgsRequired parameters were NULL or not properly specified.
ResolvePrefixResolve a namespace prefix to the UID of its namespace URI within a tag's scope.
ERR xml::ResolvePrefix(OBJECTPTR Object, STRVIEW Prefix, INT TagID, UINT * Result)
ParameterDescription
PrefixThe namespace prefix to resolve. Use an empty string for the default namespace.
TagIDThe tag ID defining the starting scope for namespace resolution.
ResultReceives the resolved namespace URI hash.

This method resolves a namespace prefix to its corresponding namespace URI hash by examining namespace declarations within the specified tag's hierarchical scope. The resolution process:

  1. Walks up the tag hierarchy from the specified tag to the root.
  2. Examines xmlns:prefix and xmlns attributes in each tag to find the declaration.
  3. Returns the UID of the first matching namespace URI found.

This approach correctly handles nested namespace scopes and prefix redefinitions.

Error Codes
OkayThe prefix was successfully resolved.
SearchThe prefix could not be resolved in any accessible scope, or TagID did not identify a tag.
NullArgsRequired arguments were not specified correctly.
SearchSearches for XML elements using XPath and XQuery expressions with optional callback processing.
ERR xml::Search(OBJECTPTR Object, STRVIEW Expression, FUNCTION Callback, INT * Result)
ParameterDescription
ExpressionA valid XQuery expression.
CallbackOptional reference to a callback function for processing multiple matches.
ResultUID of the first matching tag. When Callback is defined, this is the first matching tag processed.

The Search method provides the primary mechanism for locating XML elements within the document structure using XPath and XQuery expressions. The method supports both single-result queries and comprehensive tree traversal with callback-based processing for complex operations.

When no callback function is provided, Search returns the first matching element and terminates the search immediately. This is optimal for simple queries where only the first occurrence is required.

When a callback function is specified, Search calls it for each matching element until the query completes, the callback returns an error, or the callback returns ERR::Terminate.

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

The callback should return ERR::Okay to continue processing, or ERR::Terminate to halt the search immediately. Other callback errors are returned to the caller.

Note: If an error occurs, check the ErrorMsg field for a custom error message containing further details.

Error Codes
OkayA matching tag was found (or callback processing completed successfully).
TerminateTermination requested
SearchNo matching tag could be found for the specified expression.
NoDataThe XML document contains no data to search.
NewObjectNewObject() failed to produce a new object
NullArgsThe Expression was empty.
SerialiseSerialise part of the XML tree to an XML string.
ERR xml::Serialise(OBJECTPTR Object, INT Index, XMF Flags, STRING * Result)
ParameterDescription
IndexIndex to a source tag for which serialisation will start. Set to zero to serialise the entire tree.
FlagsUse INCLUDE_SIBLINGS to include siblings of the tag found at Index.
ResultThe resulting string is returned in this parameter.

The Serialise() method will serialise all or part of the XML data tree to a string.

The string will be copied into the caller-provided Result parameter.

Error Codes
OkayThe XML string was successfully serialised.
NotFoundThe specified tag Index does not exist in the XML structure.
NoDataNo information has been loaded into the XML object.
NullArgsRequired parameters were NULL or not properly specified.
SetAttribAdds, updates and removes XML attributes.
ERR xml::SetAttrib(OBJECTPTR Object, INT Index, XMS Attrib, STRVIEW Name, STRVIEW Value)
ParameterDescription
IndexIdentifies the tag that is to be updated.
AttribAttribute index to update, or NEW, UPDATE, UPDATE_ONLY or REMOVE.
NameNew attribute name. If empty during indexed updates, the name is not changed. If Attrib is UPDATE, UPDATE_ONLY or REMOVE, this name is used to find the attribute.
ValueString containing the new value for the attribute.

This method updates existing XML tag attributes, creates new attributes and clears content.

The data for the attribute is defined in the Name and Value parameters. Use an empty string if no data is to be associated with the attribute. Set Attrib to XMS::REMOVE to remove an attribute, or to clear element content if Name is empty.

NOTE: The attribute at position 0 declares the name of the tag and should not normally be accompanied with a value declaration. However, if the tag represents content within its parent, then the Name must be left empty and the Value string will determine the content.

Error Codes
OkayOperation successful.
SearchThe tag identified by Index or the attribute identified by Name could not be found.
ArgsInvalid arguments passed to function
OutOfRangeThe Attrib value is outside the tag's attribute array.
ReadOnlyThe XML object is read-only.
NullArgsFunction call missing argument value(s)
SetTagNamespaceSet the namespace for a specific XML tag.
ERR xml::SetTagNamespace(OBJECTPTR Object, INT TagID, INT NamespaceID)
ParameterDescription
TagIDThe unique identifier of the XML tag.
NamespaceIDThe UID of the namespace to assign.

This method assigns a namespace to an XML tag using the namespace's UID.

Error Codes
OkayThe namespace was successfully assigned to the tag.
NotFoundThe specified tag was not found.
NullArgsRequired arguments were not specified correctly.
SortSorts XML tags to your specifications.
ERR xml::Sort(OBJECTPTR Object, STRVIEW XPath, STRVIEW Sort, XSF Flags)
ParameterDescription
XPathSort everything under the specified tag, or empty to sort the entire top level.
SortA sorting instruction string.
FlagsOptional flags.

The Sort method is used to sort a single branch of XML tags in ascending or descending order. An XPath is required that refers to the tag containing each item that will be sorted. To sort the root level, use an empty XPath.

The Sort parameter is used to specify a list of sorting instructions. The format for the Sort string is Tag:Attrib,Tag:Attrib,.... The Tag indicates the tag name that should be identified for sorting each node, and child tags are supported for this purpose. Wildcard filtering is allowed and a Tag value of * will match every tag at the requested XPath level. The optional Attrib value names the attribute containing the sort string. To sort on content, do not define an Attrib value (use the format Tag,Tag,...).

Error Codes
OkayThe XML object was successfully sorted.
TerminateTermination requested
SearchThe provided XPath failed to locate a tag.
NewObjectNewObject() failed to produce a new object
ReadOnlyThe XML object is in read-only mode and cannot be modified.
NullArgsRequired parameters were NULL or not properly specified.
ValidateDocumentValidate the XML document against the currently loaded schema.
ERR xml::ValidateDocument(OBJECTPTR Object)

This method performs structural and simple type validation of the document using the loaded XML Schema. It returns ERR::Okay when the document conforms to the schema. Validation failures return an error and populate ErrorMsg with the reason where available.

Error Codes
OkayValidation completed successfully.
InvalidDataThe document structure, namespace or element content failed schema validation.
SearchThe schema does not define the root element present in the document.
NoDataThe XML document does not contain any parsed tags.
NoSupportNo schema has been loaded for this XML object.
XML class documentation © Paul Manias © 2001-2026

XMF Type

Standard flags for the XML class.

NameDescription
XMF::HAS_SCHEMAAutomatically defined when a schema has been loaded into the XML object.
XMF::INCLUDE_COMMENTSBy default, comments are stripped when parsing XML input unless this flag is specified.
XMF::INCLUDE_SIBLINGSInclude siblings when building an XML string (GetXMLString() only)
XMF::INCLUDE_WHITESPACEBy default the XML parser will skip content between tags when they contain pure whitespace. Setting this flag will retain all whitespace.
XMF::INDENTIndent the output of serialised XML to improve readability.
XMF::LOCK_REMOVEPrevents removal of tags from the XML tree. This specifically affects the RemoveTag and RemoveXPath methods.
XMF::LOG_ALLPrint extra log messages.
XMF::NAMESPACE_AWAREEnable namespace processing during parsing.
XMF::NEWCreates an empty XML object on initialisation - if the Path field has been set, the source file will not be loaded.
XMF::NO_ESCAPETurns off escape code conversion.
XMF::OMIT_TAGSPrevents tags from being output when the XML is serialised (output content only).
XMF::PARSE_ENTITYEnables parsing of DOCTYPE entities.
XMF::PARSE_HTMLAutomatically parse HTML escape codes.
XMF::READABLEIndent the output of serialised XML to improve readability.
XMF::READ_ONLYEdits to the document are not permitted.
XMF::STANDALONEAutomatically defined when the XML declaration specifies standalone="yes".
XMF::STRIP_CDATADo not serialise CDATA sections. Note that this option is used as a parameter, not an object flag.
XMF::STRIP_CONTENTStrip all content from incoming XML data.
XMF::STRIP_HEADERSXML headers found in the source data will not be included in the parsed results.
XMF::WELL_FORMEDBy default, the XML class will accept badly structured XML data. This flag requires that XML statements must be well-formed (tags must balance) or an ERR::BadData error will be returned during processing.
XML module documentation © Paul Manias © 2001-2026

XMI Type

Tag insertion options.

NameDescription
XMI::CHILDInsert as the first child of the target.
XMI::CHILD_ENDInsert as the last child of the target.
XMI::NEXTInsert as the next tag of the target.
XMI::PREVInsert as the previous tag of the target.
XML module documentation © Paul Manias © 2001-2026

XMS Type

For SetAttrib()

NameDescription
XMS::NEWAdds a new attribute. Note that if the attribute already exists, this will result in at least two attributes of the same name in the tag.
XMS::REMOVERemoves the named attribute, or clears element content if the name is empty.
XMS::UPDATEAs for UPDATE_ONLY, but if the attribute does not exist, it will be created.
XMS::UPDATE_ONLYSetAttrib will find the target attribute and update it. It is not possible to rename the attribute when using this technique. ERR::Search is returned if the attribute cannot be found.
XML module documentation © Paul Manias © 2001-2026

XSF Type

Options for the Sort method.

NameDescription
XSF::CHECK_SORTTells the algorithm to check for a 'sort' attribute in each analysed tag and if found, the algorithm will use that as the sort value instead of that indicated in the Attrib field.
XSF::DESCSort in descending order.
XML module documentation © Paul Manias © 2001-2026

XTF Type

Standard flags for XTag.

NameDescription
XTF::CDATATag represents CDATA.
XTF::COMMENTTag represents a comment of the format <!-- Comment -->.
XTF::INSTRUCTIONTag represents an instruction of the format <?xml?>.
XTF::NOTATIONTag represents a notation of the format <!XML>.
XML module documentation © Paul Manias © 2001-2026

XMLAttrib Structure

FieldTypeDescription
NameSTRINGName of the attribute
ValueSTRINGValue of the attribute
XML class documentation © Paul Manias © 2001-2026

XTag Structure

FieldTypeDescription
IDINTGlobally unique ID assigned to the tag on creation.
ParentIDINTUID of the parent tag
LineNoINTLine number on which this tag was encountered
FlagsXTFOptional flags
NamespaceIDUINTHash of namespace URI or 0 for no namespace
ReservedINTPrivate
Attribskt::vector<XMLAttrib>Array of attributes for this tag
Childrenkt::vector<XTag>Array of child tags
XML class documentation © Paul Manias © 2001-2026