9. API Reference

This reference documents the public C++ interface exposed by include/xmlio/. Function overloads are presented together under their owning namespace.

namespace xmlio

ADAT-style, C++23 XML reading, writing, and serialization facilities.

The public API deliberately exposes no libxml2 types. XMLReader provides XPath-based access, XMLWriter builds documents through a tag stack, and free read/write overloads map XML representations to C++ values. Applications extend serialization by placing overloads beside their own types so normal argument-dependent lookup finds them.

ADAT-compatible group helper spellings

inline GroupXML_t readXMLGroup(XMLReader &xml, std::string_view path, std::string_view type_name)

Compatibility wrapper for read_xml_group.

inline std::vector<GroupXML_t> readXMLVectorGroup(XMLReader &xml, std::string_view path, std::string_view type_name)

Compatibility wrapper for read_xml_vector_group.

inline std::vector<GroupXML_t> readXMLArrayGroup(XMLReader &xml, std::string_view path, std::string_view type_name)

Historical array spelling for read_xml_vector_group.

Scalar and structured reads

inline void read(XMLReader &xml, std::string_view path, std::string &output)

Read one string value from path.

Parameters:
  • xml – Reader that supplies the query context.

  • path – XPath selecting exactly one scalar node.

  • output – String replaced with the selected text, without trimming.

Throws:

QueryError – if the query does not select one scalar node.

inline void read(XMLReader &xml, std::string_view path, char &output)

Read one character from path.

Throws:

ConversionError – unless the untrimmed content has length one.

template<detail::XmlArithmetic T>
inline void read(XMLReader &xml, std::string_view path, T &output)

Strictly read one arithmetic value from path.

Parameters:
  • xml – Reader that supplies the query context.

  • path – XPath selecting exactly one scalar node.

  • output – Destination assigned after successful conversion.

Throws:
template<typename T>
void read(XMLReader &xml, std::string_view path, std::complex<T> &output)

Read a complex value represented by <re> and <im> children.

<z><re>1.5</re><im>-0.25</im></z>

Template Parameters:

T – Component type with an available read overload.

Parameters:
  • xml – Reader that supplies the query context.

  • path – XPath selecting the complex-value wrapper.

  • output – Complex value assigned after both components are read.

Throws:

QueryError – when the wrapper or a component is missing or non-unique.

template<typename First, typename Second>
void read(XMLReader &xml, std::string_view path, std::pair<First, Second> &output)

Read a pair represented by <First> and <Second> children.

Component names are capitalized for compatibility with ADAT data.

Template Parameters:
  • First – Type read from <First>.

  • Second – Type read from <Second>.

template<typename Key, typename Value, typename Compare, typename Allocator>
void read(XMLReader &xml, std::string_view path, std::map<Key, Value, Compare, Allocator> &output)

Replace a map from <elem><Key>...<Val>... records.

<masses>
  <elem><Key>pi</Key><Val>0.06906</Val></elem>
  <elem><Key>K</Key><Val>0.09698</Val></elem>
</masses>

Elements are inserted through the map’s comparator. Two XML keys that compare equivalent are therefore duplicates even if their textual forms differ.

Note

A failure after reading begins may leave output partially populated.

Parameters:
  • xml – Reader that supplies the query context.

  • path – XPath selecting the map wrapper.

  • output – Map cleared before records are read.

Throws:

QueryError – for malformed records or duplicate keys.

template<typename Key, typename Value, typename Compare, typename Allocator>
void read_map_into(XMLReader &xml, std::string_view path, std::map<Key, Value, Compare, Allocator> &output, DuplicateKeyPolicy policy = DuplicateKeyPolicy::error)

Read an XML map and merge it into an existing destination map.

Ordinary read replaces a map’s contents. This explicit operation is for catalog-style workflows that combine several XML documents. The incoming document is validated completely before the destination is changed.

Note

The destination is unchanged if parsing the incoming map fails. With DuplicateKeyPolicy::error it is also unchanged when a collision is detected.

Parameters:
  • xml – Source document.

  • path – Path selecting a map represented by <elem> records.

  • output – Existing map that receives the incoming entries.

  • policy – Action to take when an incoming key already exists in output.

Throws:

QueryError – for duplicate keys in one document or, with DuplicateKeyPolicy::error, a collision with output.

template<typename T, typename Allocator>
void read(XMLReader &xml, std::string_view path, std::vector<T, Allocator> &output)

Read a compact arithmetic vector or a structured <elem> vector.

Arithmetic vectors also accept <elem> input to ease migration between historical formats.

Note

A read failure may leave output partially populated.

Parameters:
  • xml – Reader that supplies the query context.

  • path – XPath selecting the sequence wrapper.

  • output – Vector replaced by values in document order.

Throws:
template<typename T, typename Allocator>
void read(XMLReader &xml, std::string_view path, std::list<T, Allocator> &output)

Read a list using the same representation as a vector.

Parameters:
  • xml – Reader that supplies the query context.

  • path – XPath selecting the sequence wrapper.

  • output – List replaced only after the temporary vector is read fully.

template<typename T, std::size_t Size>
void read(XMLReader &xml, std::string_view path, std::array<T, Size> &output)

Read exactly Size values into a fixed-size array.

Parameters:
  • xml – Reader that supplies the query context.

  • path – XPath selecting the sequence wrapper.

  • output – Array replaced only after conversion and size validation succeed.

Throws:

QueryError – if the input value count differs from Size.

template<typename T>
void read(XMLReader &xml, std::string_view path, std::optional<T> &output)

Read a value when present, otherwise reset the optional.

Note

Invalid present values still propagate their query or conversion error.

Parameters:
  • xml – Reader that supplies the query context.

  • path – XPath tested for existence and read when present.

  • output – Optional reset for a missing path and replaced after a successful read.

template<typename T>
T read(XMLReader &xml, std::string_view path)

Return a newly constructed value read from path.

Template Parameters:

T – Default-constructible type with a discoverable read overload.

Returns:

Fully populated value.

template<typename T>
bool read_optional(XMLReader &xml, std::string_view path, T &output)

Conditionally read into an existing destination.

Note

Query and conversion errors from a present value still propagate.

Returns:

false without modifying output when path is missing; true after a successful read.

template<typename T>
std::optional<T> read_optional(XMLReader &xml, std::string_view path)

Conditionally construct and return a value.

Note

Query and conversion errors from a present value still propagate.

Returns:

std::nullopt for a missing path, otherwise a populated optional.

template<typename T>
void read_many(XMLReader &xml, std::string_view path, std::vector<T> &output)

Read every scalar sibling selected by one XPath expression.

Unlike container read, path selects the repeated values themselves, for example "hadron/mass", rather than their common parent.

Parameters:
  • xml – Reader that supplies the query context.

  • path – XPath selecting zero or more scalar nodes.

  • output – Vector replaced in XPath document order.

Throws:
  • QueryError – if path is not a node-set query or selects a structured value.

  • ConversionError – for an invalid arithmetic item; the diagnostic path includes its zero-based result index.

Scalar and structured writes

inline void write(XMLWriter &xml, std::string_view path, std::string_view value)

Write one string child element.

Parameters:
  • xml – Writer whose current element becomes the new child’s parent.

  • path – Name of the child element, not an XPath expression.

  • value – Unescaped text; XMLWriter performs XML escaping.

inline void write(XMLWriter &xml, std::string_view path, const std::string &value)

std::string overload for writing one string child element.

inline void write(XMLWriter &xml, std::string_view path, const char *value)

C-string overload; a null pointer writes an empty child element.

inline void write(XMLWriter &xml, std::string_view path, char value)

Write one character in a child element.

template<detail::XmlArithmetic T>
inline void write(XMLWriter &xml, std::string_view path, const T &value)

Write one arithmetic child element.

Conversion is locale-independent, floating-point values use round-trip precision, and booleans are written as true or false.

template<typename T>
void write(XMLWriter &xml, std::string_view path, const std::complex<T> &value)

Write a complex value using <re> and <im> children.

template<typename First, typename Second>
void write(XMLWriter &xml, std::string_view path, const std::pair<First, Second> &value)

Write a pair using <First> and <Second> children.

template<typename Key, typename Value, typename Compare, typename Allocator>
void write(XMLWriter &xml, std::string_view path, const std::map<Key, Value, Compare, Allocator> &values)

Write a map as <elem><Key>...<Val>... records.

Records follow map iteration order, which is comparator order for std::map.

template<typename T, typename Allocator>
void write(XMLWriter &xml, std::string_view path, const std::vector<T, Allocator> &values)

Write an arithmetic vector compactly or records as <elem> children.

User-defined element types are serialized by an unqualified call to write, allowing argument-dependent lookup to find overloads in the type’s namespace.

template<typename T, typename Allocator>
void write(XMLWriter &xml, std::string_view path, const std::list<T, Allocator> &values)

Write a list using the same compact-or-structured rule as a vector.

template<typename T, std::size_t Size>
void write(XMLWriter &xml, std::string_view path, const std::array<T, Size> &values)

Write a fixed-size array using the vector representation.

template<typename T>
void write(XMLWriter &xml, std::string_view path, const std::optional<T> &value)

Write an optional child only when it contains a value.

Note

An empty optional produces no XML node; there is no nil marker.

template<typename Range>
void write_many(XMLWriter &xml, std::string_view path, const Range &values)

Write every range item as a repeated sibling named path.

The range has no wrapper element. An empty range therefore emits nothing.

void write(XMLWriter &xml, std::string_view path, const XMLReader &value)

Embed a reader’s root element inside a new element named path.

Throws:

WriterError – if the source has no root or insertion fails.

void write(XMLWriter &xml, std::string_view path, const XMLBufferWriter &value)

Embed a buffer writer’s root inside a new element named path.

Throws:

WriterError – if the source has no root or insertion fails.

Unnamed text and XML insertion operators

inline XMLWriter &operator<<(XMLWriter &xml, std::string_view value)

Append string-view text to the current writer element.

inline XMLWriter &operator<<(XMLWriter &xml, const std::string &value)

Append std::string text to the current writer element.

inline XMLWriter &operator<<(XMLWriter &xml, const char *value)

Append C-string text to the current writer element.

inline XMLWriter &operator<<(XMLWriter &xml, char value)

Append one character to the current writer element.

template<detail::XmlArithmetic T>
inline XMLWriter &operator<<(XMLWriter &xml, const T &value)

Append one locale-independent arithmetic value to the current element.

XMLWriter &operator<<(XMLWriter &xml, const XMLReader &value)

Append a reader’s root XML directly to the current element.

XMLWriter &operator<<(XMLWriter &xml, const XMLBufferWriter &value)

Append a buffer writer’s root XML directly to the current element.

Typedefs

using AttributeList = std::vector<Attribute>

Ordered attributes supplied when opening or creating an XML tag.

Namespace declarations should appear before qualified attributes that use them. Empty Attribute entries are skipped, allowing optional attributes to be assembled without branching.

using GroupXML_t = GroupXml

Legacy spelling retained for straightforward ADAT migration.

Enums

enum class DuplicateKeyPolicy

Select how read_map_into handles keys already in a destination.

Duplicate keys within a single XML map are always rejected. This policy only controls collisions between a newly read map and entries already present in the caller’s destination map.

Values:

enumerator error

Reject the merge and leave the destination unchanged.

enumerator keep_existing

Retain the destination value and ignore the incoming one.

enumerator overwrite

Replace the destination value with the incoming one.

Functions

GroupXml read_xml_group(XMLReader &xml, std::string_view path, std::string_view type_name)

Extract one typed XML subtree.

Parameters:
  • xml – Source reader.

  • path – XPath expression selecting one element.

  • type_name – Relative path of the type identifier inside that element.

Throws:

QueryError – if the group or type identifier is absent, non-unique, or non-scalar.

Returns:

Self-contained subtree with path set to "/" + path.

std::vector<GroupXml> read_xml_vector_group(XMLReader &xml, std::string_view path, std::string_view type_name)

Extract every <elem> child from an array of typed XML subtrees.

Parameters:
  • xml – Source reader.

  • path – XPath expression selecting the array container.

  • type_name – Relative path of each element’s type identifier.

Throws:

QueryError – if path is not unique or an element lacks a valid type.

Returns:

Groups in document order, each with path set to /elem.

inline bool exists(const XMLReader &xml, std::string_view path)

Free-function form of XMLReader::exists.

Parameters:
  • xml – Reader supplying the XPath context.

  • path – XPath expression to test.

inline int count(const XMLReader &xml, std::string_view path)

Free-function form of XMLReader::count.

Parameters:
  • xml – Reader supplying the XPath context.

  • path – Node-set XPath expression to count.

inline std::string get_text(const XMLReader &xml, std::string_view path)

Free-function form of XMLReader::text.

Parameters:
  • xml – Reader supplying the XPath context.

  • path – XPath selecting exactly one scalar node.

inline void push(XMLWriter &xml, std::string_view path)

Free-function ADAT spelling for XMLWriter::push.

Parameters:
  • xml – Writer whose stack receives the new element.

  • path – Element name; despite the compatibility name, this is not XPath.

inline void pop(XMLWriter &xml)

Free-function ADAT spelling for XMLWriter::pop.

Throws:

WriterError – if the writer stack is empty.

class Attribute
#include <attribute.hpp>

Name/value pair attached to an XML element.

Numeric constructors use the same locale-independent representation as normal element serialization. A namespace prefix is stored in qualified prefix:name form. Attribute does not validate XML names or namespace declarations; XMLWriter validates them when the attribute is attached.

ADAT-compatible spellings

inline const std::string &getName() const noexcept
Returns:

Same qualified name as name.

inline const std::string &getValue() const noexcept
Returns:

Same serialized value as value.

inline bool isEmpty() const noexcept
Returns:

Same empty-state test as empty.

Public Functions

Attribute() = default

Construct an empty sentinel attribute, which writers ignore.

inline Attribute(std::string name, std::string value)

Construct a string-valued attribute.

Parameters:
  • name – Unqualified or already-qualified XML attribute name.

  • value – Unescaped value; XMLWriter performs XML escaping.

template<typename T>
inline Attribute(std::string name, const T &value)

Construct an arithmetic-valued attribute.

Parameters:
  • name – Unqualified or already-qualified XML attribute name.

  • value – Value serialized with the classic locale.

inline Attribute(std::string prefix, std::string name, std::string value)

Construct a qualified string-valued attribute.

Parameters:
  • prefix – Namespace prefix, or empty for an unqualified name.

  • name – Local attribute name.

  • value – Unescaped attribute value.

template<typename T>
inline Attribute(std::string prefix, std::string name, const T &value)

Construct a qualified arithmetic-valued attribute.

Parameters:
  • prefix – Namespace prefix, or empty for an unqualified name.

  • name – Local attribute name.

  • value – Value serialized with the classic locale.

inline const std::string &name() const noexcept
Returns:

Qualified attribute name.

inline const std::string &value() const noexcept
Returns:

Serialized attribute value.

inline bool empty() const noexcept
Returns:

true when no attribute name was supplied.

class ConversionError : public xmlio::XmlError
#include <error.hpp>

Reports a scalar XML value that cannot be converted to a C++ type.

Conversion errors are distinct from QueryError: the XPath succeeded and selected a scalar node, but its text did not satisfy the requested C++ type.

Public Functions

inline ConversionError(std::string_view path, std::string_view value, std::string_view target_type)

The path and unmodified input text remain available for structured error reporting. The target type is included in what().

Parameters:
  • path – XPath expression used to obtain the value.

  • value – Text that failed conversion.

  • target_type – Descriptive name of the requested C++ type.

inline const std::string &path() const noexcept
Returns:

XPath expression used to obtain the value.

inline const std::string &value() const noexcept
Returns:

Original XML text that failed conversion.

struct GroupXml
#include <group.hpp>

An XML subtree paired with the type identifier stored inside it.

This is the standard-library replacement for ADAT’s GroupXML_t. It lets a factory retain a complete model definition until the concrete model type is selected from id. Reparse xml with XMLReader and use path as the root expected by the downstream model parser.

Public Members

std::string xml

Serialized subtree, including its selected root element.

std::string id

Scalar value read from the caller-selected type field.

std::string path

Absolute root path expected after reparsing xml.

class ParseError : public xmlio::XmlError
#include <error.hpp>

Reports malformed XML or an input source that cannot be opened.

Parse errors are raised while constructing or reopening XMLReader. The message includes the filename and libxml2 diagnostic when available.

class QueryError : public xmlio::XmlError
#include <error.hpp>

Reports an invalid XPath expression or an unexpected query result.

Examples include querying a closed reader, selecting the wrong number of nodes, requesting scalar text from a structured element, and duplicate map keys. The original query path remains available through path.

Public Functions

inline QueryError(std::string_view path, std::string_view reason)

The composed what() message has the form XML query ‘path: reason`.

Parameters:
  • path – XPath expression associated with the failure.

  • reason – Human-readable description of the failed query contract.

inline const std::string &path() const noexcept
Returns:

XPath expression associated with the failure.

class WriterError : public xmlio::XmlError
#include <error.hpp>

Reports invalid writer state or a failed output operation.

Writer-state failures include writing without an open element, closing an empty tag stack, creating multiple roots, and using undeclared namespace prefixes. File open, serialization, and write failures use the same category.

class XMLBufferWriter : public xmlio::XMLWriter
#include <writer.hpp>

Named in-memory writer used when XML is consumed as a string.

This type adds no state to XMLWriter. Its distinct name preserves the ADAT API vocabulary and selects reader/serialization overloads unambiguously.

Public Functions

XMLBufferWriter() = default

Construct an empty in-memory writer.

inline explicit XMLBufferWriter(std::string_view root_name)

Construct an in-memory writer with an open document root.

class XmlError : public std::runtime_error
#include <error.hpp>

Base class for every exception raised by xmlio.

Catch this type when an application wants one boundary for parser, query, conversion, and writer failures. Catch a derived class when recovery depends on the failure category.

Subclassed by xmlio::ConversionError, xmlio::ParseError, xmlio::QueryError, xmlio::WriterError

class XMLFileWriter : public xmlio::XMLWriter
#include <writer.hpp>

Buffered XML writer associated with an output filename.

The document is persisted by flush, close, or destruction. Explicit close is preferred when the caller needs to observe write errors. Destruction suppresses output exceptions because they cannot be reported safely from a destructor. Unlike XMLWriter, a file writer is neither copyable nor movable; its file association remains tied to the original object.

Public Functions

XMLFileWriter() = default

Construct a file writer without opening an output file.

explicit XMLFileWriter(const std::string &filename, bool write_prologue = true)

Associate the writer with filename without opening a root tag.

Note

The file is not touched until flush or close.

Parameters:
  • filename – Destination path written by flush, close, or destruction.

  • write_prologue – Include the XML declaration when persisted.

XMLFileWriter(const std::string &filename, std::string_view root_name, bool write_prologue = true)

Associate a file and immediately open root_name.

Parameters:
  • filename – Destination path written by flush, close, or destruction.

  • root_name – Document root opened immediately.

  • write_prologue – Include the XML declaration when persisted.

void open(const std::string &filename, bool write_prologue = true)

Associate a file, closing and writing any previous association first.

Note

The newly associated file is not written until flush or close.

void flush()

Write the current document while keeping the file association.

Throws:

WriterError – if no file is associated or writing fails.

inline bool fail() const noexcept
Returns:

Whether the most recent output operation failed.

inline bool is_open() const noexcept
Returns:

Whether an output filename is associated with this writer.

void close()

Write the document and clear the file association.

Calling close() on an already closed writer is harmless. If writing fails, the association is retained so the caller may inspect or retry.

Throws:

WriterError – if the final write fails.

class XMLReader
#include <reader.hpp>

Owns or shares a parsed XML document and evaluates XPath queries.

A top-level reader owns its libxml2 document. A subreader created with XMLReader(parent, path) shares that document but changes the context used for relative XPath expressions. Absolute expressions beginning with / continue to address the document root.

Reader objects are movable but not copyable. Subreaders are the explicit, low-cost way to share a document. A subreader keeps the document alive even after its parent is closed or destroyed. Mutating a shared document through set or set_text is visible through every reader that shares it.

XPath expressions are evaluated relative to the reader’s context element unless they begin with /. Operations that read a scalar require exactly one matching node; collection operations such as texts accept zero or more.

Input lifecycle

void open(const std::string &filename)

Replace the current document with XML loaded from a file.

Throws:

ParseError – if filename cannot be opened or parsed.

void open(std::istream &input)

Replace the current document with XML read from a stream.

Throws:

ParseError – if the stream fails or its contents are not valid XML.

void open(const XMLBufferWriter &writer)

Replace the current document with an in-memory writer’s XML.

Throws:

ParseError – if the writer has no valid document root.

void load_from_file(const std::string &filename)

Explicit spelling for loading a file.

Throws:

ParseError – if filename cannot be opened or parsed.

void load_from_string(std::string_view xml)

Explicit spelling for parsing XML text.

Throws:

ParseError – if xml is malformed or has no root element.

void close() noexcept

Release this reader’s document reference and query context.

Other readers sharing the document remain valid. Calling close() on an already closed reader is harmless.

XPath queries

bool exists(std::string_view path) const
Parameters:

path – XPath expression evaluated at this reader’s context.

Throws:

QueryError – if the reader is closed or XPath evaluation fails.

Returns:

For a node set, whether at least one node was selected; for an XPath boolean, its value; otherwise true for a successful scalar result.

int count(std::string_view path) const
Parameters:

path – XPath expression evaluated at this reader’s context.

Throws:

QueryError – if path does not return a node set.

Returns:

Number of selected nodes, including zero.

std::string text(std::string_view path) const

Read text from one scalar element or attribute.

Scalar elements may contain text, CDATA, and comments, but no child elements. Character data is returned exactly as provided by libxml2; string reads do not trim surrounding whitespace.

Parameters:

path – XPath selecting one element, attribute, text, or CDATA node.

Throws:

QueryError – unless path selects exactly one scalar node.

Returns:

The selected node’s text content.

std::vector<std::string> texts(std::string_view path) const

Read scalar text from every node selected by path.

Throws:

QueryError – if path is not a node-set expression or any selected node is not scalar.

Returns:

Values in XPath document order; an empty selection returns an empty vector.

std::string attribute(std::string_view path, std::string_view name) const

Read attribute name from the unique element at path.

Throws:

QueryError – unless the composed path/@name selects one attribute.

Returns:

Attribute text without numeric conversion.

ADAT-style typed access

inline void get(std::string_view path, std::string &result) const

Read a string without trimming meaningful surrounding whitespace.

Parameters:
  • path – XPath selecting exactly one scalar node.

  • result – Destination replaced only after the query succeeds.

inline void get(std::string_view path, char &result) const

Read exactly one character.

Throws:

ConversionError – unless the untrimmed XML content has length one.

template<typename T>
inline void get(std::string_view path, T &result) const

Strictly read one arithmetic value.

Conversion uses the classic C locale and rejects trailing non-whitespace data. Boolean input accepts true, false, and 1, 0 spellings.

Throws:
  • QueryError – if the query does not select one scalar node.

  • ConversionError – if the selected text is not a complete value of T.

inline void getAttribute(std::string_view path, std::string_view name, std::string &result) const

Read a string-valued attribute from one selected element.

Parameters:
  • path – XPath selecting the owning element.

  • nameAttribute name, including a prefix when applicable.

  • result – Destination replaced after a successful query.

template<typename T>
inline void getAttribute(std::string_view path, std::string_view name, T &result) const

Strictly read an arithmetic-valued attribute.

Throws:
  • QueryError – if the composed attribute query is not unique.

  • ConversionError – if the attribute is not a complete value of T.

Diagnostic and serialization output

void evaluateXPath(std::string_view path)

Evaluate and retain an XPath result for printQueryResult.

A later call replaces the retained result. This compatibility operation is stateful; ordinary query functions evaluate and return results directly.

void printQueryResult(std::ostream &output) const

Print the result retained by evaluateXPath.

Note

Prints a diagnostic message when no result has been retained.

void print(std::ostream &output) const

Print this reader’s context element without an XML declaration.

void printRoot(std::ostream &output) const

Print the document root element.

void printCurrentContext(std::ostream &output) const

Print the root element, or element children of a derived context.

This preserves the historical ADAT behavior: for a subreader, the context wrapper itself and non-element children are omitted.

void printXPathNode(std::ostream &output, std::string_view path) const

Print every node selected by path in document order.

Throws:

QueryError – when the query is not a node set or selects no nodes.

std::string str() const
Returns:

Entire document including its XML declaration, or empty if closed.

std::string root_str() const
Returns:

Serialized document root without a declaration, or empty if closed.

std::string context_str() const
Returns:

Serialized context element without a declaration, or empty if closed.

std::string xpath_str(std::string_view path) const
Throws:

QueryError – when the query is not a node set or selects no nodes.

Returns:

Serialized nodes selected by path, separated by newlines.

Public Functions

XMLReader()

Construct a closed reader that can later load an input source.

Querying a closed reader raises QueryError. Call one of the open or load_from_* functions before querying it.

explicit XMLReader(const std::string &source)

Construct from XML text or a filename using legacy source detection.

A first non-whitespace < denotes XML text; all other strings are treated as filenames. New code should prefer from_string or from_file.

Parameters:

source – XML text or a filesystem path selected by the rule above.

Throws:

ParseError – if the selected source cannot be parsed.

explicit XMLReader(std::istream &input)

Parse all XML data available from an input stream.

Parameters:

input – Stream read from its current position through end of input.

Throws:

ParseError – if the stream fails or does not contain valid XML.

explicit XMLReader(const XMLBufferWriter &writer)

Parse the current contents of an in-memory writer.

Parameters:

writer – Writer whose complete serialized document is parsed.

Throws:

ParseError – if the writer has no valid document root.

XMLReader(const XMLReader &parent, std::string_view path)

Create a reader rooted at one element selected from parent.

Parameters:
  • parent – Open reader whose document will be shared.

  • path – XPath selecting the new context element.

Throws:

QueryError – when path does not select exactly one element.

XMLReader(XMLReader&&) noexcept

Transfer a reader, including its shared document and query context.

XMLReader &operator=(XMLReader&&) noexcept

Replace this reader by moving another reader into it.

bool is_open() const noexcept
Returns:

true when a document is loaded.

bool is_derived() const noexcept
Returns:

true when this reader was rooted from another reader.

void registerNamespace(std::string_view prefix, std::string_view uri)

Register a prefix-to-URI mapping for subsequent XPath expressions.

XML namespace declarations in a document are not automatically available as XPath prefixes. Register each prefix that a query will use. Registering an existing prefix replaces its URI for this reader only.

Parameters:
  • prefix – Non-empty prefix used in XPath expressions.

  • uri – Non-empty namespace URI bound to prefix.

Throws:

QueryError – for an empty mapping or a closed reader.

void set_text(std::string_view path, std::string_view value)

Replace the content of the unique node selected by path.

For an element, libxml2 removes existing child content before installing the new text. The change is immediately visible to readers sharing the document.

Throws:

QueryError – unless path selects exactly one node.

template<typename T>
inline void set(std::string_view path, const T &value)

Serialize value and replace the scalar text at path.

Arithmetic values use the same locale-independent representation as writer serialization. String-like inputs are copied verbatim.

Public Static Functions

static XMLReader from_string(std::string_view xml)

Parse an in-memory XML document.

Parameters:

xml – Complete XML document held in memory.

Throws:

ParseError – if xml is malformed or has no root element.

Returns:

An open reader rooted at the document element.

static XMLReader from_file(const std::string &filename)

Parse an XML document from filename.

Note

Network access by the XML parser is disabled.

Throws:

ParseError – if the file cannot be opened or parsed.

Returns:

An open reader rooted at the document element.

class XMLWriter
#include <writer.hpp>

Builds one XML document in memory.

The writer maintains a stack of open elements. openTag and push add a child and make it current; closeTag and pop return to its parent. Text and attributes are always written to the current element. The libxml2 document is hidden behind a private implementation so users never depend on backend types.

Exactly one document root is permitted. Most write operations require an open current element and throw WriterError when the stack is empty. Closing the root leaves a complete document that can still be serialized, saved, or parsed by XMLReader.

Subclassed by xmlio::XMLBufferWriter, xmlio::XMLFileWriter

ADAT-compatible structural operations

void openSimple(std::string_view tag_name)

Open a scalar element.

void closeSimple()

Close the current scalar element; throws if none is open.

void openStruct(std::string_view tag_name)

Open a structured element.

void closeStruct()

Close the current structure; throws if none is open.

General tag operations

void openTag(std::string_view tag_name)

Open an unqualified child element and make it current.

Throws:

WriterError – for an empty name or a second document root.

void openTag(std::string_view prefix, std::string_view tag_name)

Open a child element qualified by a declared namespace prefix.

Parameters:
  • prefix – Prefix declared on an ancestor element.

  • tag_name – Local element name without the namespace prefix.

Throws:

WriterError – if the prefix is unavailable.

void openTag(std::string_view tag_name, const AttributeList &attributes)

Open an unqualified child element and attach attributes.

An xmlns attribute declares the default namespace for this element.

void openTag(std::string_view prefix, std::string_view tag_name, const AttributeList &attributes)

Open a qualified child element and attach attributes.

The prefix may be declared by an xmlns:prefix entry in attributes or inherited from an ancestor.

void closeTag()

Close the current element and return to its parent.

Throws:

WriterError – if no element is open.

void emptyTag(std::string_view tag_name)

Append an empty unqualified child without changing writer depth.

void emptyTag(std::string_view prefix, std::string_view tag_name)

Append an empty qualified child without changing writer depth.

Throws:

WriterError – if prefix has not been declared.

void emptyTag(std::string_view tag_name, const AttributeList &attributes)

Append an empty child with attributes without changing writer depth.

void emptyTag(std::string_view prefix, std::string_view tag_name, const AttributeList &attributes)

Append an empty qualified child with attributes.

The namespace prefix may be declared in attributes.

Text output

void write(std::string_view value)

Append escaped string text to the current element.

Throws:

WriterError – if no element is open or text allocation fails.

void write(const char *value)

Append a C string; a null pointer is written as empty text.

void write(char value)

Append one character as text.

template<typename T>
inline void write(const T &value)

Append a locale-independent arithmetic value to the current element.

Floating-point output uses enough digits for round-trip conversion and booleans are emitted as true or false.

void writeXML(std::string_view xml_fragment)

Parse and append a well-formed XML fragment below the current element.

Elements, text, CDATA, and comments are preserved. Blank wrapper text is ignored. Parser network access is disabled.

Throws:

WriterError – if the fragment is malformed, cannot be copied, or has no valid insertion point.

void write_element(std::string_view name, std::string_view value)

Append a named scalar child element without changing final depth.

Throws:

WriterError – if name is invalid or there is no valid parent.

inline void write(std::string_view name, std::string_view value)

Convenience overload for a named string child.

inline void write(std::string_view name, const std::string &value)

Convenience overload for a named std::string child.

inline void write(std::string_view name, const char *value)

Write a named C-string child; null becomes an empty element.

inline void write(std::string_view name, char value)

Write a named child containing one character.

template<typename T>
inline void write(std::string_view name, const T &value)

Append a named child containing one arithmetic value.

Current-element attributes

void set_attr(std::string_view name, std::string_view value)

Set or replace a string-valued attribute on the current element.

Qualified names require their prefix to have been declared. The special names xmlns and xmlns:prefix create namespace declarations.

Throws:

WriterError – if no element is open or a prefix is unavailable.

inline void set_attr(std::string_view name, const std::string &value)

std::string convenience overload for set_attr.

inline void set_attr(std::string_view name, const char *value)

C-string overload; a null value becomes an empty attribute.

template<typename T>
inline void set_attr(std::string_view name, const T &value)

Set or replace an arithmetic-valued attribute.

Public Functions

XMLWriter()

Construct an empty writer with no root element.

explicit XMLWriter(std::string_view root_name)

Construct a writer and open root_name as its document root.

Throws:

WriterError – if root_name is empty or cannot form an element.

XMLWriter(XMLWriter&&) noexcept

Transfer the document and current-element stack from another writer.

XMLWriter &operator=(XMLWriter&&) noexcept

Replace this writer with another writer’s document and stack.

inline void push(std::string_view tag_name)

ADAT-style alias for openStruct.

Parameters:

tag_name – Child element to open and make current.

inline void pop()

ADAT-style alias for closeStruct.

bool empty() const noexcept
Returns:

true if no document root has been created.

std::size_t depth() const noexcept

A newly opened root has depth one; a complete document whose root has been closed has depth zero but is not empty.

Returns:

Number of currently open elements.

std::string str(bool prologue = true) const
Parameters:

prologue – Include the XML declaration when true.

Throws:

WriterError – if serialization fails.

Returns:

Complete document, or an empty string when no root exists.

std::string printRoot() const
Returns:

Root element without an XML declaration, or empty if absent.

void print(std::ostream &output, bool prologue = true) const

Serialize the complete document to output.

Parameters:
  • output – Stream that receives the serialization.

  • prologue – Include the XML declaration when true.

void save(const std::string &filename, bool prologue = true) const

Replace filename with the complete XML document.

Throws:

WriterError – if the file cannot be opened or fully written.

Protected Attributes

std::unique_ptr<Impl> impl_

Opaque libxml2 document and current-element stack.

namespace detail

Functions

inline std::string trim_ascii(std::string_view value)

Remove leading and trailing ASCII whitespace from a string view.

Parameters:

value – Input text; embedded whitespace is preserved.

Returns:

An owning string containing the trimmed range.

template<typename T>
std::string scalar_to_text(const T &value)

Convert a scalar to its portable XML text representation.

Floating-point values use max_digits10, and booleans use true or false. The classic C locale prevents application locale settings from changing XML output, for example by replacing a decimal point with a comma.

Parameters:

value – Arithmetic or stream-insertable scalar value.

Returns:

Owning string suitable for element or attribute content.

template<typename T>
T scalar_from_text(std::string_view value, std::string_view path)

Strictly convert scalar XML text to an arithmetic C++ value.

Leading and trailing ASCII whitespace is accepted for numbers and booleans. Character conversion is intentionally different: the original untrimmed text must contain exactly one character.

Parameters:
  • value – XML character data to convert.

  • path – Query path included in ConversionError diagnostics.

Throws:

ConversionError – when conversion fails or trailing data remains.

Returns:

Converted value of type T.

template<typename Range>
std::string compact_sequence_text(const Range &values)

Serialize an arithmetic range as one space-separated text value.

template<XmlArithmetic T, typename Output>
void parse_compact_sequence(std::string_view text, std::string_view path, Output &&append)

Parse a compact sequence and pass each converted value to a sink.

Parameters:
  • text – Space-separated scalar tokens.

  • path – Source path used to construct indexed conversion diagnostics.

  • append – Callable accepting each converted T.

template<typename T>
void read_structured_elements(XMLReader &xml, std::string_view path, std::vector<T> &output)

Read repeated <elem> records through argument-dependent lookup.