Recursive AI

XML documents

All onehtml docs

How OneHtml reads and writes XML: MutableDocument.ParseXml, the error document, and the XML serialization. This is the normative behaviour text; where the specifications leave room, the choice is stated with the reason.

Specifications: XML 1.0 (Fifth Edition), Namespaces in XML 1.0 (Third Edition), HTML Standard sections 14.2 "Parsing XML documents", 14.3 "Serializing XML fragments" and 14.4 "Parsing XML fragments", and DOM Parsing and Serialization 5.2 "XML serialization".

Entry points

CallWhat it does
MutableDocument.ParseXml(text, contentType, options)Parses XML text into a new document. contentType is application/xml (default), text/xml, application/xhtml+xml, image/svg+xml or another +xml type; it is lower-cased and becomes ContentType. Any other type is an ArgumentException.
MutableDocument.ParseFromString(text, type)DOMParser.parseFromString: the four XML types go to ParseXml, text/html to the HTML parser, anything else is TypeError.
MutableNode.SerializeToXml(requireWellFormed)XMLSerializer.serializeToString. Default flag is unset, as for XMLSerializer.
MutableNode.SerializeChildrenToXml(requireWellFormed)The children only, as innerHTML gives in an XML document. Default flag is set.
MutableNode.SetInnerXml(xml), MutableDocument.ParseXmlFragment(xml, context)The XML fragment parsing algorithm (HTML 14.4): the text is parsed as the content of the context element with its namespace prefixes in scope; text that is not well-formed throws kind SyntaxError and changes nothing.
GetHtml, SerializeNode, SerializeChildren, SetInnerHtml, InsertAdjacentHtml, ParseFragmentUnchanged: the HTML algorithms in every document, an XML document included. An embedding that implements innerHTML and outerHTML picks the XML calls above when IsXmlDocument is true. This keeps the behaviour of these members as released; the XML routes are additive.

IsXmlDocument is true for every document ParseXml makes. Snapshot().Document of an XML document has IsXmlContent set: selector names and attribute names match case-sensitively (HTML 4.16 folds case only for HTML elements of HTML documents), and xml:lang counts for :lang() and Node.Language.

What the parser accepts

The input is a string already decoded; no encoding sniffing happens, and an encoding pseudo-attribute in the XML declaration is checked for syntax only.

Before parsing: a leading U+FEFF is dropped; CR LF and a lone CR read as LF (XML 1.0 2.11); a lone surrogate reads as U+FFFD, as text that arrived as UTF-8 would; the WPT parsererror page requires the replacement.

Grammar covered: XML declaration (at the very start only), comments, processing instructions, doctype with public and system identifier, the internal subset, elements and empty-element tags, attributes, character data, CDATA sections, character and entity references, and the Namespaces in XML constraints (prefix declarations, xml and xmlns reservations, unbound prefixes, duplicate expanded attribute names, NCName local parts).

Tree: each construct becomes the DOM node of the same name. A CDATA section is a Text node with IsCDataSection (node type 4); adjacent text and entity replacement text join into one Text node. An element's name is kept as written (no case folding), in the namespace its prefix resolves to; an xmlns or xmlns:p attribute is an attribute in the XMLNS namespace. An HTML-namespace template has its children in its template content, as the HTML parser does (HTML 14.2). No custom element definition is looked up and no script runs; scripts are inert text. An HTML element with a customelementregistry attribute, and every element inside it, gets a null custom element registry that stays null (HTML 13.2.6.1, as in the HTML parser); elements without it follow the document's registry. A document made by ParseXml is one a window browses to and has the global registry, as a parsed HTML document does (DOM 4.5 Document, HTML 4.13.4), so defining a name upgrades the parsed elements and createElement constructs; a document made by ParseFromString (DOMParser), CreateEmpty, CreateHtmlDocument or ImplementationCreateDocument has no browsing context and a null registry.

Doctype and entities

  • The doctype node has the name and the public and system identifiers. The internal subset is read but not kept; the serializer does not write it (DOM Parsing 5.2.1.7).
  • General entities declared in the internal subset by literal values expand where referenced, in content and in attribute values. First declaration wins (XML 1.0 4.2). Predefined entities lt gt amp quot apos always work. Character references in an entity value are replaced when the entity is declared; general references inside it when it is used.
  • A declared entity with an external identifier is recorded and never read: in content it stands for nothing; in an attribute value it is not well-formed (XML 1.0 3.1, 4.4.4).
  • Parameter entities are not expanded. A reference to one, or any external subset, marks the document "may have declarations we cannot see": an undefined entity reference then stands for nothing instead of being an error (XML 1.0 4.1 well-formedness constraint "Entity Declared" applies only when the document has no external subset or parameter-entity references), unless standalone='yes'.
  • HTML 14.2: when the doctype's public identifier (white space collapsed) is one of the eleven listed — -//W3C//DTD XHTML 1.0 Transitional//EN, XHTML 1.1, XHTML 1.0 Strict, XHTML 1.0 Frameset, XHTML Basic 1.0, XHTML 1.1 plus MathML 2.0, XHTML 1.1 plus MathML 2.0 plus SVG 1.1, MathML 2.0, and the three WAPFORUM XHTML Mobile — the HTML named character references (the same table as the HTML parser, entities.json) are defined as entities. Nothing is fetched. Any other identifier leaves them undefined. Internal declarations win over them.
  • Entity references inside entity values and the markup an entity holds are parsed in place; the replacement text of an entity used in content must be balanced (open and close tags inside it pair up) [XML 1.0 4.3.2].

Not well-formed text: the error document

HTML 14.2 says an XML parser stops at the first well-formedness error and the user agent shows an error; browsers' DOMParser returns a document whose only child is a parsererror element. ParseXml does the same: no exception is thrown. The result is a new XML document (same ContentType) whose root has one element parsererror in MutableDocument.ParserErrorNamespace (http://www.mozilla.org/newlayout/xml/parsererror.xml) holding one text node XML Parsing Error: <message>\nLocation: \nLine Number <n>, Column <m>:. XmlError carries Message, Line, Column and Offset (1-based line and column in the normalized text, 0-based offset). The message wording is ours and may change; the position is of the first error. Nothing partial of the original document is kept. The element's text follows what browsers show; WPT only checks the element and namespace.

Limits

All checked before the work they guard; a violation throws DomException kind LimitExceeded, not the error document, because the input may be well-formed.

LimitDefaultGuards
MaxXmlInputLength64 Mi charactersinput size, checked before anything else
MaxEntityExpansionChars4 Mithe total length of replacement text of all entity references in one parse (billion laughs)
MaxEntityNesting32depth of entities used inside entities
MaxDepth, MaxAttributesPerElement, MaxNodes, MaxTotalAttributes, MaxValueLength, MaxNamesas for any MutableDocumenttree depth, attributes, nodes, one text or attribute value, distinct names

Nothing recurses on input depth: open elements, namespace bindings (a stack with per-prefix chains) and entity frames are explicit lists; the serializer walks with an explicit stack. An entity that refers to itself, directly or through others, is a well-formedness error (reference loop).

Serialization

SerializeToXml is DOM Parsing 5.2.1 exactly, with a single table of prefix lists whose additions are undone on leaving an element (equivalent to copying the namespace prefix map per element). Summary of what it does that readers get wrong:

  • An element whose namespace equals the inherited default is written unprefixed; otherwise its own prefix is kept if declared for its namespace in scope, else the last prefix in scope, else a prefix declaration or a default declaration is added.
  • Attributes with a namespace get the preferred prefix in scope for it, or a generated ns1, ns2, … with a declaration (the counter is per serialization and does not check for clashes with existing ns declarations, as the spec says; WPT has a test that expects the duplicate).
  • A prefix-less xmlns attribute in no namespace is dropped (error under require-well-formed) (the specification asks for this only in the flag case).
  • Void HTML elements with no children are <br />; other HTML-namespace elements with no children are <div></div>; other empty elements are <x/>. An HTML template writes its content's children (HTML 14.3).
  • Attribute values escape & " < > and tab, LF, CR as &#9;, &#xA;, &#xD;. Text escapes & < >. Comments, processing instructions and CDATA sections are written as they are.
  • Doctype identifiers are always in double quotes, even around an identifier that holds one (PUBLIC """ """), because browsers do and WPT xml-serialization.xhtml expects it; the draft's quote-switching is used only when require-well-formed is set, where it is needed to read back. (evidence: WPT).
  • Require-well-formed throws InvalidStateError for: a document without a document element; an element or attribute local name with a colon or not an XML Name; an attribute xmlns in no namespace; two attributes with one namespace and local name; a character XML cannot hold in text, attribute values, comments, processing instructions or CDATA; -- or a trailing - in a comment; ]]> in CDATA; ?> in a processing instruction; a processing instruction target with a colon or equal to xml (ASCII case-insensitive); a doctype public id with a character outside PubidChar or a system id holding both quote kinds; the prefix xmlns on an element; an XMLNS-namespace declaration of the XMLNS namespace; an empty prefix declaration.
  • SerializeChildrenToXml begins with no inherited namespace, so children in a namespace carry their own declaration (<a xmlns="http://www.w3.org/1999/xhtml">). It is the algorithm of 5.2.1 applied to the node's children, which is what WPT innerhtml-03.xhtml shows.

Source map and editing

XML documents have no source map. MutableDocument.XmlSource returns the exact text given to ParseXml (a well-formed document only), which is the lossless no-edit round trip: the input, character for character. It is not updated by edits. Document.Apply on a snapshot of an XML document is refused (EditResult reports a failure naming the reason) because there is no byte range to splice; edit the MutableDocument and serialize it. Lossless byte-range editing of XML is not built. (Documents parsed with Document.Parse and an XML ContentType are still read by the HTML parser, as before, and edit as before; ParseXml is the XML parser.)

Downstream

  • Selectors: type and attribute names match case-sensitively on every element of an XML document; the HTML attribute-value case-insensitivity list does not apply either.
  • Cascade: StyleContext and the cascade read the snapshot as any other; the user-agent sheet applies to HTML-namespace elements, so an XHTML page gets the HTML defaults and an element in no namespace gets none.
  • :lang() and Node.Language read xml:lang as the XML-namespace lang attribute.
  • The accessibility tree builds on the snapshot unchanged.

Not covered

  • External subsets and external entities (never loaded), parameter entities, ATTLIST defaults and normalization by declared type, and validation. ELEMENT, ATTLIST and NOTATION declarations are skipped.
  • XML 1.1, XInclude, XSLT, and <?xml-stylesheet?> processing (it is a processing instruction node like any other).
  • Lossless editing of XML (above).
  • WPT domparsing/ pages that need script or a window: listed in testdata/wpt/domparsing/README.md with the reason for each.

Tests

  • XmlTests: well-formedness errors (one case per rule), namespaces, entity limits and billion laughs, the eleven public identifiers, depth, line-end normalization, serialization round trip.
  • WptDomParsingXmlTests: the XML parts of WPT domparsing/, translated file by file.
  • Fuzz target xml: parse never throws except for limits; parsed trees serialize well-formed and the serialization is a fixed point of parse and serialize. testdata/xml/seeds/ holds the seeds.

Findings kept

  • A carriage return in text (from &#13;) is written raw by the XML serialization, as DOM Parsing specifies, and reads back as a line feed (XML 1.0 2.11): the one place serialize-then-parse is not the identity. Attribute values write it as &#xD;, so they round-trip. Found by the xml fuzz target; the target skips the stability check for output holding a CR.
  • A doctype with a public identifier and an empty system identifier is written <!DOCTYPE n PUBLIC "p"> (DOM Parsing 5.2.1.7), which XML does not accept back (ExternalID needs the system literal after PUBLIC). The parser refuses it, as WPT DOMParser-parseFromString-xml-doctype.html requires.