Skip to content
James Conway edited this page Nov 25, 2026 · 7 revisions

parsec-xml is Parsec's XML parser: XML 1.0 (Fifth Edition) and Namespaces in XML 1.0 (Third Edition), not validating. It has its own tokenizer and its own tree, and shares nothing with the HTML parser but parsec-base. XML's rules apply all the way through: a well-formedness error is fatal, a name is its namespace and local part, and entities are expanded only as far as you allow. It's M14.

On this page: Install · Parsing · Names and namespaces · Attributes · Entities and the DTD · What Parsec never reads · Limits · Errors · Positions · Bytes in · Writing XML back · Conformance · XPath · From Python, JavaScript and C · Speed

Note

parsec-xml ships from the next release. Until then, depend on it from Git: parsec-xml = { git = "https://github.com/parsec-html/parsec" }.

Install

cargo add parsec-xml

It depends on parsec-base and encoding_rs, and nothing else. You don't compile the HTML parser to use it (Architecture says why). The xpath feature adds parsec-xpath and its one dependency, stacker, and still no HTML parser (XPath).

Parsing

let feed = r#"<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
  <entry><title>Ships &amp; ports</title></entry>
</feed>"#;
let doc = parsec_xml::parse(feed)?;
let root = doc.root_element();
assert_eq!(doc.name(root).unwrap().local, "feed");
assert_eq!(doc.text(root).trim(), "Ships & ports");

parse uses the default Options; parse_with takes your own. A Document is an arena: NodeIds are numbered in document order from the document node at 0, so descendants(n) is a range of ids, not a walk. Walk with parent, first_child, last_child, next_sibling, prev_sibling, children and ancestors; ask what a node is with kind:

NodeKind What it is
Document the root, above the document element
Doctype the <!DOCTYPE>; doc.doctype() has its name, public and system IDs, and the internal subset as written
Element(Name) an element
Text(&str) character data, line ends normalized and references replaced; adjacent text is one node
CData(&str) a CDATA section's contents
Comment(&str) a comment
ProcessingInstruction { target, data } a PI
EntityRef(&str) a reference to an entity Parsec didn't read (below)

doc.text(n) is XPath's string(): every text and CDATA node under n, in order. doc.xml_decl() has the declaration's version, encoding and standalone. Documents are Send and Sync.

Names and namespaces

Every element and attribute name is resolved when it's read:

let doc = parsec_xml::parse(r#"<r xmlns="urn:d" xmlns:p="urn:p"><p:c p:x="1" y="2"/></r>"#)?;
let c = doc.first_child(doc.root_element()).unwrap();
let name = doc.name(c).unwrap();
assert_eq!((name.qname, name.prefix, name.local, name.namespace), ("p:c", "p", "c", "urn:p"));
assert_eq!(doc.attribute(c, "urn:p", "x"), Some("1"));
// An unprefixed attribute is in no namespace, whatever the default.
assert_eq!(doc.attribute(c, "", "y"), Some("2"));
assert_eq!(doc.lookup_namespace(c, ""), Some("urn:d"));

Names, prefixes and URIs are interned once per document. The namespace rules are errors, as Namespaces in XML says: an unbound prefix (undeclared-prefix), a name that isn't a qualified name (invalid-qname), two attributes with the same namespace and local name (duplicate-attribute), xmlns:p="" (Namespaces 1.0 can't undeclare a prefix), binding xml to anything but its namespace or xmlns at all (invalid-namespace-declaration), and a colon in an entity name, PI target or notation name (colon-in-name).

Set Options::namespaces to false for XML 1.0 without namespaces: then a name is any XML name, colons and all, in no namespace.

xml:lang and xml:space are inherited: doc.xml_lang(n) is the nearest xml:lang on n or above it, and doc.preserves_space(n) says whether the nearest xml:space is preserve.

Attributes

doc.attributes(n) gives them in start-tag order, each with its Name, its value, its span, and whether it was specified or defaulted by the DTD. Values are normalized as XML says: references replaced, each tab, newline and line end a space, and for an attribute the internal subset declares as anything but CDATA, spaces trimmed and collapsed. Namespace declarations are attributes here too, in the http://www.w3.org/2000/xmlns/ namespace, so is_namespace_declaration() picks them out.

Entities and the DTD

The internal subset is read as XML asks of a processor that doesn't validate:

  • General entities are expanded in content and attribute values; parameter entities between declarations are expanded too. doc.entities() lists what was declared, the first declaration of each name.
  • <!ATTLIST> defaults are applied, including a defaulted xmlns:p, which binds its prefix.
  • <!ELEMENT> and <!NOTATION> are checked for syntax; doc.notations() lists the notations.
  • The five predefined entities (lt, gt, amp, apos, quot) always work.
let doc = parsec_xml::parse(r#"<!DOCTYPE a [
  <!ENTITY who "the &#38;#60;world&#38;#62;">
  <!ATTLIST a lang CDATA "en">
]><a>hello, &who;</a>"#)?;
let a = doc.root_element();
assert_eq!(doc.text(a), "hello, the <world>");
assert_eq!(doc.attribute(a, "", "lang"), Some("en"));

A character reference in an entity's value is replaced when the entity is declared, and the result is parsed as markup when it's used. So <!ENTITY e "&#60;"> holds a bare <, and &e; in content is an error; for a < that stays text, write &#38;#60;, as above.

A reference to an entity inside itself is recursive-entity; to an undeclared one, undeclared-entity; to an unparsed (NDATA) one in content, unparsed-entity-reference. An entity whose text opens an element must close it (unbalanced-entity).

What Parsec never reads

Parsec never fetches a URL or opens a file. The external subset (<!DOCTYPE a SYSTEM "a.dtd">), external general entities and external parameter entities are left unread, and the spec's rules for a processor that doesn't read them apply:

  • doc.warnings() says what wasn't read: external-dtd-not-loaded, entity-not-loaded (once per entity), and declarations-skipped. None is an error.
  • A reference to an external entity in content stays in the tree as NodeKind::EntityRef. In an attribute value it's an error (external-entity-in-attribute), as the spec says.
  • After a parameter entity that wasn't read, later <!ENTITY> and <!ATTLIST> declarations are skipped, since the unread one may have declared them first (XML 1.0, 5.1).
  • When the DTD has parts Parsec didn't read and the document isn't standalone="yes", a reference to an undeclared entity becomes an EntityRef rather than an error: the unread part may declare it.

There's no switch to turn fetching on. If you need an external DTD's entities, read the file yourself and put its declarations in the internal subset.

Limits

Option Default What it stops
limits.max_depth 2,048 (DEFAULT_MAX_DEPTH) elements nested deeper: too-deep
max_entity_depth 16, never past ENTITY_DEPTH_CEILING (64) entity references nested deeper: entity-too-deep
entity_allowance, entity_ratio 1 MiB, 8 expansion past 1 MiB plus 8 bytes per byte of input, every expansion counted: entity-expansion-limit
limits.max_steps none more than this many nodes, attributes and expansions: step-limit
limits.max_input none input over this size: input-too-large

So a billion laughs (ten entities, each ten references to the last) stops in milliseconds, and so does the quadratic blowup (one 100 KB entity referenced 200,000 times). Open elements are on the parser's own stack, so nesting costs no recursion: with max_depth: None, a million nested elements parse, walk and serialize without touching the call stack. Only entity expansion recurses, and its ceiling keeps that shallow. Many attributes, many namespace declarations, many entities and long names all cost time in proportion; the tests in crates/parsec-xml/tests/hostile.rs check each.

Errors

Every well-formedness error is fatal, as XML says. There's no recovery mode. An Error has the Diagnostic (a stable code, its span, a message, and labels) and its position, the line and column from parsec_base::LineIndex:

let e = parsec_xml::parse("<a>\n  <b></a>").unwrap_err();
assert_eq!(e.code(), "mismatched-end-tag");
assert_eq!(e.to_string(), "2:6: `</a>` closes `<b>` [mismatched-end-tag]");
// The label points at the start tag it doesn't match.
assert_eq!(e.diagnostic.labels[0].message, "opened here");

Positions

Every node and attribute has a Span, a byte range in the input: an element's from its start tag's < to its end tag's >, an attribute's from its name to its closing quote. Nodes an entity produced have the span of the reference that produced them. LineIndex turns any offset into a line and column, in characters or UTF-16 units.

Bytes in

let latin1 = b"<?xml version='1.0' encoding='ISO-8859-1'?><p>caf\xe9</p>";
let parsed = parsec_xml::parse_bytes(latin1, &Default::default())?;
assert_eq!(parsed.document.text(parsed.document.root()), "café");

The encoding comes from the byte order mark, then from the first bytes' pattern (UTF-16 without a BOM), then from the declaration, as XML's Appendix F says; with none of them, it's UTF-8. Labels are looked up as the WHATWG Encoding Standard has them, as browsers do for XML (so ISO-8859-1 decodes as windows-1252). Decoding is strict: a byte that isn't the encoding is invalid-byte-sequence at its position, a declaration that contradicts the BOM is encoding-mismatch, and UCS-4 and EBCDIC are unsupported-encoding. Parsed::text is the decoded text the spans point into; for UTF-8 it borrows your bytes.

Writing XML back

doc.to_xml() writes the document: the declaration (without an encoding, since it's a string), the <!DOCTYPE> with its internal subset as written, and the tree, every prefix and namespace declaration as it was. Entities come out expanded, but for those Parsec didn't read. doc.write_xml(node, &mut out) writes one subtree, and an element written alone takes along the namespace declarations it's in the scope of:

let doc = parsec_xml::parse("<a xmlns='urn:d' xmlns:p='urn:p'><b xmlns:p='urn:q'><p:c/></b></a>")?;
let b = doc.first_child(doc.root_element()).unwrap();
let mut out = String::new();
doc.write_xml(b, &mut out);
assert_eq!(out, r#"<b xmlns:p="urn:q" xmlns="urn:d"><p:c/></b>"#);

What comes out parses back to the same tree; the conformance run checks that on every document.

Conformance

The W3C XML Conformance Test Suite runs in cargo test (crates/parsec-xml/tests/xmlconf.rs), its last release pinned by address and SHA-256 and downloaded by crates/parsec-xml/scripts/fetch-xmlconf.sh. Each CI run publishes the counts in its summary.

Cases
Pass 1,915
of which match their canonical output byte for byte 223
Fail 0
Skipped: XML 1.1 or Namespaces 1.1 274
Skipped: XML 1.0 before the Fifth Edition 310
Skipped: error cases, which a processor may report or not 27
Skipped: not-wf with the fault in an external entity, which Parsec never reads 59

valid and invalid documents must parse (a processor that doesn't validate accepts invalid ones), not-wf ones must be errors, and a valid one with canonical output must give exactly that. Every document that parses is also written back out and must parse to the same thing. One case, ibm-valid-P29-ibm29v01.xml, parses but isn't compared: its expected output puts a PI from the internal subset before the <!DOCTYPE>, which no canonical form does.

XPath

Turn on the xpath feature and a Document is a tree XPath 1.0 can query. parsec_xml::xpath is parsec-xpath, re-exported without its HTML tree, so no HTML parser comes into your build:

parsec-xml = { version = "0.3", features = ["xpath"] }

Build the Index once per document; every query reads it, and none builds it.

use parsec_xml::xpath::{Doc, Index, Item, NoExtensions, Value, XPath};

let doc = parsec_xml::parse(r#"<feed xmlns="http://www.w3.org/2005/Atom">
  <entry><title>Ships</title></entry><entry><title>Ports</title></entry>
</feed>"#)?;
let index = Index::build(&doc, &[0]);
let atom = [("a".to_string(), "http://www.w3.org/2005/Atom".to_string())];
let query = XPath::new("//a:entry[2]/a:title")?;
if let Value::Nodes(hits) = query.evaluate(Doc::new(&doc, &index), 0, &[], &atom, &NoExtensions)? {
    if let Item::Node(n) = hits[0] {
        assert_eq!(doc.text(parsec_xml::NodeId::from_index(n as usize)), "Ports");
    }
}

What changes from XPath over HTML:

  • Names compare exactly: //Item doesn't find <item>.
  • A query's prefixes come from the namespaces you run it with, not the document's. An unprefixed name test is in no namespace, so elements in a default namespace need a prefix bound to it, as a: is above.
  • xmlns and xmlns:* aren't attributes; //@* leaves them out. They're on the namespace axis instead: //item/namespace::* gives xml first, then the bindings in scope, the outermost element's first. A namespace node's name is its prefix ("" for the default) and its string value is its URI. xmlns="" takes the default namespace away and leaves no node for it.
  • In a result, Item::Ns { owner, decl } is a namespace node; Doc::namespace_at(decl) gives its prefix and URI.
  • id() finds xml:id and attributes the internal subset declares ID. lang() reads xml:lang on the node or above it.
  • The doctype isn't a node: /node() is the document element and the comments and PIs around it.

libxml2's XPath document tests (test/XPath/tests against test/XPath/docs, from the bench/libxml2 submodule at v2.15.4) run in cargo test -p parsec-xml --features xpath. Each result is printed as libxml2 prints it and compared with libxml2's: all 84 queries pass, the 5 on the namespace axis among them.

From Python, JavaScript and C

Every binding has the XML parser, with the same options, the same errors and the same limits as the Rust crate. Each takes text or bytes, and bytes are decoded as Bytes in says.

Python, parsec_html.xml:

from parsec_html import xml

doc = xml.parse(b"<?xml version='1.0' encoding='ISO-8859-1'?><feed xmlns='http://www.w3.org/2005/Atom'><title>caf\xe9</title></feed>")
doc.encoding                     # 'windows-1252'
feed = doc.root                  # the document element; doc.document is its parent
feed.namespace                   # 'http://www.w3.org/2005/Atom'
feed.first_child.text()          # 'café'
feed.first_child.source_range    # byte offsets into the bytes you passed
doc.xml                          # written back out

try:
    xml.parse("<a>\n  <b></a>")
except xml.XMLSyntaxError as e:  # a ValueError
    print(e.code, e.line, e.column)   # mismatched-end-tag 2 6

A node's names follow the HTML parser's: tag, parent, next, prev, first_child, last_child, children, attributes (a dict by name as written), text(), source_range, position. Namespaces add local_name, prefix, namespace, attribute(local_name, namespace=None) and attribute_list. kind is "element", "text", "cdata", "comment", "processing-instruction", "doctype", "entity-reference" or "document". The limits are keywords: namespaces=, max_depth=, max_entity_depth=, entity_allowance=, entity_ratio=. A document can't be changed, so threads share one freely, on free-threaded Python too.

JavaScript, WebAssembly or the native Node build, the same API in both:

import { parseXml, parseXmlBytes } from "parsec-web";

const doc = parseXml(feedText, { maxDepth: 256 });
const feed = doc.documentElement;            // doc.root is the document node
feed.namespaceURI;
feed.firstChild.getAttributeNS("http://www.w3.org/1999/xlink", "href");
doc.xml;

Nodes have DOM names: nodeType, nodeName, localName, prefix, namespaceURI, nodeValue, textContent, parentNode, firstChild, lastChild, nextSibling, previousSibling, childNodes, children, getAttribute, getAttributeNS, hasAttribute, getAttributeNames, span, xml. attributes is an array of { name, localName, prefix, namespaceURI, value, specified, span }. An error is a SyntaxError with code, line and column. Spans index a string in UTF-16 units and bytes in bytes. The options are namespaces, maxDepth, maxEntityDepth, entityAllowance and entityRatio. XML adds 113 KB to the .wasm (44 KB gzipped); a build with --no-default-features leaves it out.

C, in parsec.h:

parsec_xml_document *doc = NULL;
parsec_xml_error *err = NULL;
if (parsec_xml_parse(bytes, len, NULL, &doc, &err) != PARSEC_OK) {
    fprintf(stderr, "%zu:%zu: %s\n", err->line, err->column, err->message);
    parsec_xml_error_free(err);
    return;
}
parsec_node feed = parsec_xml_document_element(doc);
size_t n;
const char *ns = parsec_xml_namespace_uri(doc, feed, &n);    /* borrowed */
for (parsec_node c = parsec_xml_first_child(doc, feed); c != PARSEC_NO_NODE;
     c = parsec_xml_next_sibling(doc, c)) {
    parsec_xml_attr a;
    for (size_t i = 0; parsec_xml_attr_at(doc, c, i, &a) == PARSEC_OK; i++)
        printf("%.*s = %.*s\n", (int)a.name_len, a.name, (int)a.value_len, a.value);
}
char *out = parsec_xml_serialize(doc, parsec_root(), &n);   /* owned */
parsec_string_free(out);
parsec_xml_document_free(doc);

The functions mirror the HTML ones with a parsec_xml_ prefix: parent, first_child, last_child, next_sibling, prev_sibling, node_type (with PARSEC_NODE_ENTITY_REFERENCE, 5), node_name, local_name, prefix, namespace_uri, node_value, attr_count, attr_at, attr_get, attr_get_ns, text, serialize, node_span, line_col, warnings_count and warnings_get. There are no edits, since a document can't be changed, and no JSON dump: the walk above reaches everything, without a JSON parser on your side. parsec_xml_options holds flags (PARSEC_XML_NO_NAMESPACES), max_depth, max_entity_depth, entity_allowance and entity_ratio, each 0 for its default. An error is PARSEC_ERR_XML (or PARSEC_ERR_TOO_LARGE over 4 GiB) with a parsec_xml_error: code, message, line, column. Offsets are into the bytes you passed, whatever their encoding.

Speed

On 102 MB of real XML (sitemaps, RSS and Atom feeds, SVGs, the XML spec, and a Wikipedia dump slice), Parsec parses 1,314 MB/s, 2.66 times libxml2's 495 and four times roxmltree's 327, ahead of both on every document. Benchmarks has the table, the method and how to run it.

Clone this wiki locally