Parasol Framework
  • Gallery
  • API
  • Wiki
  • GitHub
    • Audio
    • Core
    • Display
    • Fluid
    • Font
    • Network
    • Vector
    • Audio
    • Sound
    • File
    • MetaClass
    • Module
    • StorageDevice
    • Task
    • Thread
    • Time
    • Compression
    • Config
    • Script
    • XML
    • 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
    • NetSocket
    • Proxy
    • Vector
    • VectorClip
    • VectorColour
    • VectorEllipse
    • VectorFilter
    • VectorGradient
    • VectorGroup
    • VectorImage
    • VectorPath
    • VectorPattern
    • VectorPolygon
    • VectorRectangle
    • VectorScene
    • VectorShape
    • VectorSpiral
    • VectorText
    • VectorTransition
    • VectorViewport
    • VectorWave

XML Class

Provides an interface for the management of structured data.

The XML class is designed to provide robust functionality for creating, parsing and maintaining XML data structures. It supports both well-formed and loosely structured XML documents, offering flexible parsing behaviours to accommodate various XML formats. The class includes comprehensive support for XPath 2.0 queries, content manipulation and document validation.

The class has been designed in such a way as to accommodate other structured data formats such as JSON and YAML. In this way, the class not only provides XML support but also serves as Parasol's general-purpose structured data handler. It also makes it trivial to convert between different structured data formats, and benefit from the cross-application use of features, such as applying XPath 2.0 queries on data originating from YAML.

Data Loading and Parsing

XML documents can be loaded into an XML object through multiple mechanisms:

The Path field allows loading from file system sources, with automatic parsing upon initialisation. The class supports LoadFile() caching for frequently accessed files, improving performance for repeated operations.

The Statement field enables direct parsing of XML strings, supporting dynamic content processing and in-memory document construction.

The Source field provides object-based input, allowing XML data to be sourced from any object supporting the Read action.

For batch processing scenarios, the Path or Statement fields can be changed post-initialisation, causing the XML object to clear old data and parse the new. This approach optimises memory usage by reusing existing object instances rather than creating new ones.

Document Structure and Access

Successfully parsed XML data is accessible through the Tags field, which contains a hierarchical array of XMLTag structures. Each XMLTag represents a complete XML element including its attributes, content and child elements. The structure maintains the original document hierarchy, enabling both tree traversal and direct element access.

C++ developers benefit from direct access to the Tags field, represented as pf::vector<XMLTag>. This provides efficient iteration and element access with standard STL semantics. Altering tag attributes is permitted and methods to do so are provided in the C++ header for objXML and XMLTag, with additional functions in the xml namespace. Check the header for details.

Fluid developers need to be aware that reading the Tags field generates a copy of the entire tag structure - it should therefore be read only as needed and cached until the XML object is modified.

Not Supported

DTD processing and validation is intentionally not supported. While the class can parse DOCTYPE declarations, it does not load or validate against external DTDs as this is now a legacy technology. Use XML Schema (XSD) for validation instead.

Structure

The XML class consists of the following fields:

Access
NameTypeComment
  DocTypeSTRINGRoot element name from 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::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.

  PublicIDSTRINGPublic identifier for external DTD
  ReadOnlyINTPrevents modifications and enables caching for a loaded XML data source.

This field can be set to true prior to initialisation of an XML object that will use an existing data source. It prevents modifications to the XML object. If the data originates from a file path, the data may be cached to optimise parsing where the same data is used across multiple XML objects.

  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.

  StartINTSet a starting cursor to affect the starting point for some XML operations.

When using any XML function that creates an XML string (e.g. SaveToObject), the XML object will include the entire XML tree by default. Defining the Start value will restrict processing to a specific tag and its children.

The Start field currently affects the SaveToObject() action and the Statement field.

  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 will return a serialised string of XML data. By default all tags will be included in the statement unless a predefined starting position is set by the Start field. The string result is an allocation that must be freed.

  SystemIDSTRINGSystem identifier for external DTD
  TagsSTRUCT []Provides direct access to the XML document structure.

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

Each XMLTag 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: Fluid 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 all parsed XML content from the object, including the complete tag hierarchy, cached data structures and internal state information. This action effectively returns the XML object to its freshly-initialised condition, ready to accept new XML data.

DataFeedProcesses and integrates external XML data into the object's document structure.
ERR acDataFeed(*Object, OBJECTID Object, DATA Datatype, APTR Buffer, INT Size)
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.
SizeThe size of the data in Buffer.

The DataFeed action provides a mechanism for supplying XML content to the object from external sources or streaming data. This action supports both complete document replacement and incremental content addition, depending on the current state of the XML object.

The action accepts data in XML or plain text format and automatically performs parsing and integration. When the object contains no existing content, the provided data becomes the complete document structure. If the object already contains parsed XML, the new data is parsed separately and appended to the existing tag hierarchy.

If the provided data contains malformed XML or cannot be parsed according to the current validation settings, the action will return appropriate error codes without modifying the existing document structure. This ensures that partial parsing failures do not corrupt previously loaded content.

Attempts to feed data into a read-only XML object will be rejected to maintain document integrity.

Example:

local xml = obj.new('xml') local err = xml.acDataFeed(nil, DATA_XML, 'First element')
GetKeyRetrieves data using XPath 2.0 queries.
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.

The XML class uses key-values for the execution of XPath 2.0 queries. Documentation of the XPath standard is out of the scope for this document, however the following examples illustrate common uses for this query language and a number of special instructions that we support:

NameDescription
/menu/submenuReturn the content of the submenu tag whose parent is the first menu.
/menu[2]/submenuReturn the content of the submenu tag whose parent is the third menu.
count(/menu)Return a count of all menu tags at the root level.
/menu/window/@titleReturn the value of the title attribute from the window tag.
exists(/menu/@title)Return 1 if a menu with a title attribute can be matched, otherwise 0.
exists(/menu/text())Return 1 if menu contains content.
//windowReturn content of the first window discovered at any branch of the XML tree (double-slash enables flat scanning of the XML tree).
ResetClears the information held in an XML object.
SaveToObjectSaves XML data to a storage object (e.g. File).
ERR acSaveToObject(*Object, OBJECTID Dest, CLASSID ClassID)
ParameterDescription
DestRefers to an object that will receive the encoded data.
ClassIDCan refer to a sub-class that should be used when encoding the data.
SetKeySets attributes and content in the XML tree using XPaths.
ERR acSetKey(*Object, CSTRING Key, CSTRING 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. Setting the Value to NULL will remove the attribute or existing content, while an empty string will keep an attribute but eliminate any associated data.

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.
SearchFailed to find the tag referenced by the XPath.
ReadOnlyChanges to the XML structure are not permitted.

Methods

The following methods are currently supported:

CountCount all tags that match a given XPath expression.
ERR xml::Count(OBJECTPTR Object, CSTRING XPath, INT * Result)
ParameterDescription
XPathA valid XPath expression string defining the elements to count. The expression must conform to XPath 2.0 syntax with Parasol extensions.
ResultPointer to an integer variable that will receive the total count of matching tags.

This method will count all tags that match a given XPath and return the value in the Result parameter. It is optimised for performance and does not modify the XML structure in any way. It is safe to call concurrently from multiple threads.

Error Codes
OkayThe count operation completed successfully.
NullArgsEither the XPath parameter or Result parameter was NULL.
FilterFilters the XML data structure to retain only a specific tag and its descendants.
ERR xml::Filter(OBJECTPTR Object, CSTRING XPath)
ParameterDescription
XPathA valid XPath expression string that identifies the target tag to retain. The expression must resolve to exactly one element for successful filtering.

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 begins by locating the target element using the provided XPath expression. Once found, a new XML structure is created containing only the matched tag and its complete descendant hierarchy. All sibling tags, parent elements (excluding the direct lineage) and unrelated branches are permanently discarded.

Error Codes
OkayThe filtering operation completed successfully and the XML structure now contains only the specified subtree.
SearchNo matching tag could be found for the specified XPath expression.
NullArgsThe XPath parameter was NULL or empty.
FindTagSearches for XML elements using XPath expressions with optional callback processing.
ERR xml::FindTag(OBJECTPTR Object, CSTRING XPath, FUNCTION * Callback, INT * Result)
ParameterDescription
XPathA valid XPath expression string conforming to XPath 2.0 syntax with Parasol extensions. Must not be NULL or empty.
CallbackOptional pointer to a callback function for processing multiple matches.
ResultPointer to an integer that will receive the unique ID of the first matching tag. Only valid when no callback is provided.

The FindTag method provides the primary mechanism for locating XML elements within the document structure using XPath 2.0 compatible 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, FindTag 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, FindTag continues searching through the entire document structure, calling the provided function for each matching element. This enables comprehensive processing of all matching elements in a single traversal.

The C++ prototype for Callback is ERR Function(*XML, XMLTag &Tag, CSTRING Attrib).

The callback should return ERR::Okay to continue processing, or ERR::Terminate to halt the search immediately. All other error codes are ignored to maintain search robustness.

Error Codes
OkayA matching tag was found (or callback processing completed successfully).
SearchNo matching tag could be found for the specified XPath expression.
NoDataThe XML document contains no data to search.
NullArgsThe XPath parameter was NULL or the Result parameter was NULL when no callback was provided.
GetAttribRetrieves the value of a specific XML attribute from a tagged element.
ERR xml::GetAttrib(OBJECTPTR Object, INT Index, CSTRING Attrib, CSTRING * Value)
ParameterDescription
IndexThe unique identifier of the XML tag to search. This must correspond to a valid tag ID as returned by methods such as FindTag().
AttribThe name of the attribute to retrieve (case insensitive). If NULL or empty, the element's tag name is returned instead.
ValuePointer to a string pointer that will receive the attribute value. Set to NULL 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 NULL or empty, the method returns the tag name itself, providing convenient access to element names without requiring separate API calls.

Performance Considerations

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.

Data Integrity

The returned string pointer references internal XML object memory and remains valid until the XML structure is modified. Callers should not attempt to modify or free the returned string. For persistent storage, the string content should be copied to application-managed memory.

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, INT Length)
ParameterDescription
IndexThe unique identifier of the XML element from which to extract content. This must correspond to a valid tag ID as returned by search methods.
BufferPointer to a pre-allocated character buffer that will receive the extracted content string. Must not be NULL.
LengthThe size of the provided buffer in bytes, including space for null termination. Must be at least 1.

The GetContent method provides efficient extraction of text content from XML elements using a shallow parsing approach. It retrieves only the immediate text content of the specified element, deliberately excluding any text contained within nested child elements. This behaviour is valuable for scenarios requiring precise content extraction without recursive tag processing.

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.

Comparison with Deep Extraction

For scenarios requiring complete text extraction including all nested content, use the Serialise() method with appropriate flags to perform deep content analysis. The GetContent method is optimised for cases where nested tag content should be excluded from the result.

If the resulting content exceeds the buffer capacity, the result will be truncated but remain null-terminated.

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.
ArgsThe Length parameter was less than 1, indicating insufficient buffer space.
BufferOverflowThe buffer was not large enough to hold the complete content. The result is truncated but valid.
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, CSTRING Name, CSTRING * Value)
ParameterDescription
NameThe name of the entity to retrieve. This must correspond to a parsed entity declaration.
ValueReceives the resolved entity value on success. The returned pointer remains valid while the XML object exists.

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 or Value parameter was NULL.
GetNamespaceURIRetrieve the namespace URI for a given namespace UID.
ERR xml::GetNamespaceURI(OBJECTPTR Object, UINT NamespaceID, CSTRING * Result)
ParameterDescription
NamespaceIDThe UID of the namespace.
ResultPointer to a string pointer that will receive 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, CSTRING Name, CSTRING * 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 or Value parameter was NULL.
GetTagReturns a pointer to the XMLTag structure for a given tag index.
ERR xml::GetTag(OBJECTPTR Object, INT Index, struct XMLTag ** Result)
ParameterDescription
IndexThe index of the tag that is being retrieved.
ResultThe XMLTag is returned in this parameter.

This method will return the XMLTag structure for a given tag Index. The Index is checked to ensure it is valid prior to retrieval, and an ERR::OutOfRange 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, CSTRING 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 to ensure document validity.
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, CSTRING 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.
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.
NullArgsRequired parameters were NULL or not properly specified.
InsertXPathInserts an XML statement in an XML tree.
ERR xml::InsertXPath(OBJECTPTR Object, CSTRING XPath, XMI Where, CSTRING 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.
XMLThe statement to process.
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 an Insert 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.
SearchThe XPath could not be resolved to a valid location.
ReadOnlyThe XML object is in read-only mode and cannot be modified.
NullArgsRequired parameters were NULL or not properly specified.
LoadSchemaLoad an XML Schema definition to enable schema-aware validation.
ERR xml::LoadSchema(OBJECTPTR Object, CSTRING 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 XPath evaluation routines that utilise schema-aware behaviour.

Error Codes
OkaySchema was successfully loaded and parsed.
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 be moved from the source index. Minimum value of 1.
DestIndexThe destination tag index. If the index exceeds the total number of tags, the value will be automatically limited to the last tag index.
WhereUse PREV or NEXT to insert behind or ahead of the target tag. Use CHILD 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 a Where of XMI::CHILD. 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, CSTRING URI, UINT * Result)
ParameterDescription
URIThe namespace URI to register. Must not be NULL or 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.
FailedThe URI was empty or invalid.
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 (neighbouring) tags that should also be deleted. A value of one or less will remove only the indicated tag and its children. The total may exceed the number of tags actually available, in which case all tags up to the end of the branch will be affected.

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 is capable of deleting multiple tags if the Total parameter is set to a value greater than 1. Each consecutive tag and its children following the targeted tag will be removed from the XML structure until the count is exhausted. This is useful for mass delete operations.

This method is volatile and will destabilise any 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, CSTRING XPath, INT Limit)
ParameterDescription
XPathAn XML path string.
LimitThe maximum number of matching tags to delete. A value of one or zero will remove 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 will be repeated so that each tag that matches the XPath will be deleted, or the Limit is reached.

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.
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, CSTRING Prefix, INT TagID, UINT * Result)
ParameterDescription
PrefixThe namespace prefix to resolve. Use empty string for default namespace.
TagIDThe tag ID defining the starting scope for namespace resolution.
ResultPointer to an integer that will receive the resolved namespace hash.

This method resolves a namespace prefix to its corresponding URI 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.
NotFoundThe specified tag was not found.
SearchThe prefix could not be resolved in any accessible scope.
NullArgsRequired arguments were not specified correctly.
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 allocated as a memory block and stored in the Result parameter. It must be freed once the data is no longer required.

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.
AllocMemoryFailed to allocate memory for the XML string result.
NullArgsRequired parameters were NULL or not properly specified.
SetAttribAdds, updates and removes XML attributes.
ERR xml::SetAttrib(OBJECTPTR Object, INT Index, XMS Attrib, CSTRING Name, CSTRING Value)
ParameterDescription
IndexIdentifies the tag that is to be updated.
AttribEither the index number of the attribute that is to be updated, or set to NEW, UPDATE or UPDATE_ONLY.
NameString containing the new name for the attribute. If NULL, the name will not be changed. If Attrib is UPDATE or UPDATE_ONLY, the Name is used to find the attribute.
ValueString containing the new value for the attribute. If NULL, the attribute is removed.

This method is used to update and add attributes to existing XML tags, as well as adding or modifying 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 the Value pointer to NULL to remove the attribute. If both Name and Value are NULL, an error will be returned.

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 set to NULL and the Value string will determine the content.

Error Codes
OkayOperation successful.
SearchThe attribute, identified by Name, could not be found.
ArgsInvalid arguments passed to function.
OutOfRangeThe Index or Attrib value is out of range.
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.
SetVariableStores a variable that can be referenced in XPath expressions.
ERR xml::SetVariable(OBJECTPTR Object, CSTRING Key, CSTRING Value)
ParameterDescription
KeyThe name of the variable (case sensitive).
ValueThe string value to store.

This method allows you to store key-value pairs that can be referenced in XPath expressions using the variable syntax $variableName. Variables are stored as strings and are made available during XPath evaluation.

Error Codes
OkayOperation successful.
ReadOnlyThe XML object is read-only.
NullArgsThe Key parameter was not specified.
SortSorts XML tags to your specifications.
ERR xml::Sort(OBJECTPTR Object, CSTRING XPath, CSTRING Sort, XSF Flags)
ParameterDescription
XPathSort everything under the specified tag, or NULL to sort the entire top level.
SortPointer to a 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 XPath of NULL.

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.
SearchThe provided XPath failed to locate a tag.
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. The Result parameter returns 1 when the document conforms to the schema, otherwise 0.

Error Codes
OkayValidation completed successfully.
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.
NullArgsThe Result parameter was not supplied.
XML class documentation © Paul Manias © 2001-2025

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::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-2025

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-2025

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::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-2025

XPVT Type

Type descriptors for XPathValue

NameDescription
XPVT::Boolean
XPVT::Date
XPVT::DateTime
XPVT::NodeSet
XPVT::Number
XPVT::String
XPVT::Time
XML module documentation © Paul Manias © 2001-2025

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-2025

XMLAttrib Structure

FieldTypeDescription
Namestd::stringName of the attribute
Valuestd::stringValue of the attribute
XML class documentation © Paul Manias © 2001-2025

XMLTag Structure

FieldTypeDescription
IDINTUnique ID assigned to the tag on creation
ParentIDINTUnique ID of the parent tag
LineNoINTLine number on which this tag was encountered
FlagsXTFOptional flags
NamespaceIDUINTHash of namespace URI or 0 for no namespace
Attribspf::vector<XMLAttrib>Array of attributes for this tag
Childrenpf::vector<XMLTag>Array of child tags
XML class documentation © Paul Manias © 2001-2025

XPathValue Structure

FieldTypeDescription
typeXPVTIdentifies the type of value stored
number_valueDOUBLE
string_valuestd::string
XML class documentation © Paul Manias © 2001-2025