Chapter 60. Parsing and creating XML documents

#include <x/xml/doc.H>

x::xml::doc empty_document=x::xml::doc::create();

x::xml::doc loaded_document=x::xml::doc::create("testxml.xml", "xinclude");

x::xml::doc is a reference to a reference-counted object that represents a parsed XML document. x::xml::docptr, x::xml::const_doc, and x::xml::const_docptr follow the usual convention for reference-counted objects for defining nullable reference pointer, and their const equivalens.

Their default create() function constructs a new, empty, XML document. Otherwise the first parameter specifies the name of the file whose contents get parsed. An exception gets thrown if an error occured during parsing.

An optional second parameter to create() gives options for parsing this XML document. The second parameter is a string that specifies one or more XML parsing options, separated by commas or spaces. The option names correspond directly to libxml's xmlParserOption flags. Each option name consists of the xmlParserOption in lower case, and without the XML_PARSE_ prefix. The example above specifies xinclude, the XML_PARSE_XINCLUDE option.

Note

The nonet/XML_PARSE_NONET option is enabled by default. Include !nonet to turn this option off.

It is also possible to parse an XML document from an arbitrary source, by using an x::xml::parser:

#include <x/xml/parser.H>
#include <x/xml/doc.H>

template<typename iter_type>
x::xml::doc parse_xml(iter_type beg_iter, iter_type end_iter)
{
    x::xml::parser parser=x::xml::parser::create("in-memory-xml");

    parser=std::copy(beg_iter, end_iter, parser);

    return parser.get()->done();
}

x::xml::parser is a reference-counted output iterator. Construct it with create() then have it iterate over a char sequence that defines an XML document. Call get() to retrieve a reference to the output iterator's underlying reference-counted object, then invoke its done() to return an x::xml::doc that represents the parsed XML document.

create()'s first required parameter is a short label, some kind of an identifier that refers to the document that gets parsed. This label gets used to refer to the document in any error messages that result from an attempt to parse it.

Note

A parsing error results in a thrown exception, which occurs during iteration.

create() also takes a second optional argument that gives parsing option, the same parsing option argument to x::xml::doc's create().