xml

    A lossless XML parser for MoonBit with UTF-16 source offsets, compact tree storage, and lazy entity decoding. About 15x faster than Milky2018/xml on the same input

    xml
    parser
    dom
    Download zip
    Author
    Version
    0.1.1
    License
    MIT
    Last updated
    11 hours ago
    Downloads
    5

    No dependencies

    #justjavac/xml

    coverage

    Lossless XML parsing with UTF-16 source offsets, namespace resolution, and lazy entity decoding. Targets native, wasm, and wasm-gc.

    #Install

    moon add justjavac/xml

    #Quick Start

    ///|
    test "parse and query" {
    let doc = @xml.parse(
    "<r xmlns:p=\"urn:p\"><p:item id=\"1\">Hi &amp; bye</p:item></r>",
    )
    let item = doc.find("item").unwrap()
    assert_eq(item.namespace_uri(), Some("urn:p"))
    assert_eq(item.get_attr("id"), Some("1"))
    assert_eq(item.text(), "Hi & bye")
    }

    find matches the qualified name as written or its local part, so find("item") and find("p:item") both find <p:item>. text() decodes entities; inner() returns the source instead.

    #Performance

    A 260 KB catalogue parses in 521 µs on native, about 15× faster than Milky2018/xml on the same input while materializing the same document, and 245× on entity-heavy text, which lazy decoding never expands. wasm reaches 24×; wasm-gc is narrower at 8.7×. Of the six XML parsers on mooncakes this is the fastest — the nearest, marianoguerra/xml, is 1.9× behind on the wasm-gc catalogue. Tables and method: benchmark/README.md.

    #Design

    • Compact tree. Nine Int32 columns indexed by node id. A node costs no heap object, and a subtree is the contiguous range (id, stop[id]), so traversal is index arithmetic.
    • Interned names, lazy values. Names compare as integers, and attribute pairs, decoded text, and namespace bindings are computed on first read — a document that is only inspected structurally never decodes an entity.
    • Lossless. Every node keeps its source range, so stringify() returns the original text and position(offset) maps back to a line and column.

    #Limits

    The parser never throws: problems are recorded in Document::error and parsing continues from the next <. No DTD validation, parameter entities, or external entities; entity replacement text expands as characters, not as markup; XML 1.1 and the full NameStartChar production are not enforced. No XInclude, XPath, or XSLT.

    #License

    MIT

    Attributes

    pub struct Attributes {
    // private fields
    }

    A read-only view of an element's attributes.

    The view borrows the document's cached [name, value, ...] pairs: creating it copies nothing, and it stays valid for as long as the document does. Names keep their authored case and prefix; values are entity-decoded.

    Lookups are linear in the number of attributes, which is the right trade for the usual handful of them. to_map builds a real map when a long list is queried repeatedly.

    test "read attributes through the view" {
    let doc = @xml.parse("<r a=\"1\" b=\"x &amp; y\"/>")
    let attrs = doc.root().unwrap().attributes()
    assert_eq(attrs.length(), 2)
    assert_eq(attrs.get("b"), Some("x & y"))
    assert_true(attrs.has("a"))
    let seen : Array[String] = []
    attrs.each(fn(name, value) { seen.push("\{name}=\{value}") })
    assert_eq(seen, ["a=1", "b=x & y"])
    }
    impl Eq for Attributes

    Attributes::each

    fn Attributes::each(self : Attributes, visit : (String, String) -> Unit) -> Unit

    Call visit with every attribute name and value, in source order.

    Nothing is allocated for the iteration itself: the callback receives the cached strings, and source order means the result is stable across runs.

    Attributes::get

    fn Attributes::get(self : Attributes, name : String) -> String?

    The decoded value of an attribute, or None when absent.

    Lookup is linear and compares names exactly, the same rules Element::get_attr applies; the difference is that this one does not go back to the element.

    Attributes::has

    fn Attributes::has(self : Attributes, name : String) -> Bool

    Whether the attribute is present, matched exactly.

    Attributes::is_empty

    fn Attributes::is_empty(self : Attributes) -> Bool

    Whether the element has no attributes at all.

    Attributes::length

    fn Attributes::length(self : Attributes) -> Int

    The number of attributes on the element.

    Attributes::to_map

    fn Attributes::to_map(self : Attributes) -> Map[String, String]

    An independent, mutable copy of the attributes as a map.

    The view itself cannot be modified; this is how a caller gets something to edit. A duplicated name keeps the value that appears last, which is also what the parser records in the view.

    CData

    pub struct CData {
    // private fields
    }

    A CDATA section.

    Its content is never decoded: <![CDATA[a &amp; b]]> yields the literal a &amp; b, seven characters that look like a reference and are not one.
    impl Eq for CData

    CData::end

    fn CData::end(self : CData) -> Int

    The offset just past the > in ]]>.

    CData::start

    fn CData::start(self : CData) -> Int

    The offset of the < in <![CDATA[.

    The range covers the whole section, delimiters included, while value returns only the content between them.

    CData::value

    fn CData::value(self : CData) -> String

    The content of a CDATA section, without the <![CDATA[ and ]]>.

    CDATA is literal by definition, so this is a slice of the source: &amp; inside a section stays five characters.

    Comment

    pub struct Comment {
    // private fields
    }

    A comment, from <!-- to -->.
    impl Eq for Comment

    Comment::end

    fn Comment::end(self : Comment) -> Int

    The offset just past the > in -->.

    Comment::start

    fn Comment::start(self : Comment) -> Int

    The offset of the < in <!--.

    The range covers the whole comment, delimiters included.

    Comment::value

    fn Comment::value(self : Comment) -> String

    The content of a comment, without the <!-- and --> delimiters.

    Cursor

    pub struct Cursor {
    // private fields
    }

    A position in a document, addressed by node id.

    A cursor is a two-field handle over the document, so moving one is a field write rather than a tree search, and a walk builds no intermediate array. Each cursor handed to a visitor is still one small struct, which is the per-node cost a walk pays.

    A cursor can also stand on the document node itself, which Cursor::kind reports as NodeKind::Document and Cursor::node reports as None.

    test "navigate with a cursor" {
    let doc = @xml.parse("<a><b id=\"1\"/><c/></a>")
    let a = doc.cursor().first_child().unwrap()
    assert_eq(a.kind(), @xml.NodeKind::Element)
    let b = a.first_child().unwrap()
    assert_eq(b.element().unwrap().get_attr("id"), Some("1"))
    assert_eq(b.next_sibling().unwrap().element().unwrap().name(), "c")
    assert_eq(b.parent().unwrap().kind(), @xml.NodeKind::Element)
    }

    Cursor::element

    fn Cursor::element(self : Cursor) -> Element?

    The element at this position, or None when the node is not an element.

    This is the bridge from a flat walk to the element API: walk hands out cursors, and this turns the ones that are elements into Element.

    test "collect elements during a walk" {
    let doc = @xml.parse("<r><a/><b/></r>")
    let names : Array[String] = []
    doc.walk(fn(cursor) {
    if cursor.element() is Some(element) {
    names.push(element.name())
    }
    })
    assert_eq(names, ["r", "a", "b"])
    }

    Cursor::first_child

    fn Cursor::first_child(self : Cursor) -> Cursor?

    The first child of this position, or None when it has none.

    The first child is the node one id past this one, because ids are assigned in document order. An empty element and a self-closing one both report None.

    Cursor::kind

    fn Cursor::kind(self : Cursor) -> NodeKind

    The kind of node this cursor stands on.

    NodeKind::Document only appears for the cursor returned by Document::cursor; every cursor produced by walking stands on a node.

    Cursor::next_sibling

    fn Cursor::next_sibling(self : Cursor) -> Cursor?

    The next sibling of this position, or None at the end of the parent.

    A node with children owns the whole id range up to its subtree end, so the next sibling starts there. Skipping a sibling therefore costs the same whether it is empty or has a thousand descendants.

    Cursor::node

    fn Cursor::node(self : Cursor) -> Node?

    The node at this position, or None for the document node.

    Unlike element, this wraps every kind, which is what a caller needs when the kind is not known in advance.

    Cursor::parent

    fn Cursor::parent(self : Cursor) -> Cursor?

    The parent position, or None for the document node.

    Walking up from the root element yields a cursor on the document, whose own parent is None. Nothing else reports None, because every node in the tree has a parent.

    DocType

    pub struct DocType {
    // private fields
    }

    A <!DOCTYPE ...> declaration.

    The declaration is recorded as written. Its internal subset is scanned for general entity declarations, and nothing else in it is interpreted.
    impl Eq for DocType

    DocType::end

    fn DocType::end(self : DocType) -> Int

    The offset just past the > that ends the declaration.

    DocType::start

    fn DocType::start(self : DocType) -> Int

    The offset of the < in <!DOCTYPE.

    The range covers the whole declaration, angle brackets included.

    DocType::value

    fn DocType::value(self : DocType) -> String

    The declaration's text between <!DOCTYPE and >, without the leading whitespace.

    For <!DOCTYPE html> this is html. The internal subset, if any, is part of the same string.

    Document

    pub struct Document {
    // private fields
    }

    A parsed XML document.

    A document owns the source string and the compact tree built from it, and every Element, Text, and Cursor obtained from it is a handle into that shared state. Handles stay valid for as long as the document does, and two handles compare equal exactly when they point at the same node of the same document.

    test "a document is the entry point" {
    let doc = @xml.parse("<r><a/></r>")
    assert_eq(doc.source(), "<r><a/></r>")
    assert_eq(doc.stringify(), "<r><a/></r>")
    assert_true(doc.is_well_formed())
    }
    impl Eq for Document

    Document::all

    fn Document::all(self : Document, query : String) -> Array[Element]

    Every element whose name matches query, in document order.

    The matching rules are those of Document::find; the result holds handles, so building it is cheap, but it is a snapshot and is not updated by later calls.

    Document::children

    fn Document::children(self : Document) -> Array[Node]

    The document's direct children, excluding the document node itself.

    This is where the prolog and any top-level comments or processing instructions appear, in source order. The array is built on each call and holds handles, so it costs one slot per child and nothing per node.

    Document::cursor

    fn Document::cursor(self : Document) -> Cursor

    A cursor at the document node.

    Cursor::kind reports NodeKind::Document here, Cursor::node returns None, and Cursor::first_child moves to the first item of the prolog.

    Document::end

    fn Document::end(self : Document) -> Int

    The offset just past the last code unit of the source.

    This is source().length(), not the end of the root element: trailing comments and whitespace after the root are part of the document.

    Document::error

    fn Document::error(self : Document) -> Int?

    The offset of the first structural problem, or None when the document is well formed.

    The parser recovers and keeps going, so this reports where recovery first happened rather than where parsing stopped. The offset is a source offset, which position turns into a line and column.

    test "an error carries its offset" {
    let doc = @xml.parse("<a>\n <b>\n</a>")
    let at = doc.error().unwrap()
    assert_eq(at, 10)
    assert_eq(doc.position(at), { line: 3, column: 1, })
    }

    Document::find

    fn Document::find(self : Document, query : String) -> Element?

    The first element whose name matches query, in document order.

    query matches the qualified name as written or the local part, so both find("p:item") and find("item") find <p:item>. Matching is case-sensitive and ignores namespaces: two prefixes bound to the same URI are still different names.

    The scan is linear in the number of nodes. For repeated queries against a large document, collect all once and index the result.

    test "find matches the local part" {
    let doc = @xml.parse(
    "<r xmlns:p=\"urn:p\"><p:item>1</p:item><item>2</item></r>",
    )
    assert_eq(doc.find("item").unwrap().text(), "1")
    assert_eq(doc.find("p:item").unwrap().text(), "1")
    assert_eq(doc.all("item").length(), 2)
    }

    Document::is_well_formed

    fn Document::is_well_formed(self : Document) -> Bool

    Whether the document parsed without structural problems.

    Equivalent to error() is None, and cheaper to read at the call site than comparing the option.

    Document::position

    fn Document::position(self : Document, offset : Int) -> Position

    The line and column of a source offset.

    Both are one-based and counted in UTF-16 code units, so offset 0 is line 1, column 1. Offsets past the end are clamped to the end of the source, and a negative offset is treated as 0.

    The scan is linear in offset, so converting many offsets one at a time is quadratic in the length of the document; converting them in ascending order in one pass is not.

    test "position maps offsets to lines" {
    let doc = @xml.parse("<a>\n<b/>\n</a>")
    assert_eq(doc.position(0), { line: 1, column: 1, })
    assert_eq(doc.position(4), { line: 2, column: 1, })
    assert_eq(doc.position(9), { line: 3, column: 1, })
    }

    Document::root

    fn Document::root(self : Document) -> Element?

    The document's root element, or None when it has none.

    The first element child of the document node is the root; the declaration, comments, and processing instructions that precede it are skipped, as are any that follow it.

    test "root skips the prolog" {
    let doc = @xml.parse("<?xml version=\"1.0\"?><!-- c --><r/>")
    assert_eq(doc.root().unwrap().name(), "r")
    assert_eq(doc.root().unwrap().children().length(), 0)
    }

    Document::source

    fn Document::source(self : Document) -> String

    The source text the document was parsed from, exactly as given.

    The string is not copied: it is the value that was passed to parse.

    Document::start

    fn Document::start(_self : Document) -> Int

    The offset where the document starts, always 0.

    It exists so that a document and an element can be handled by the same code through start and end.

    Document::stringify

    fn Document::stringify(self : Document) -> String

    The document's source text, unchanged.

    Nothing is re-serialized: the tree stores offsets into the original string, so a round trip returns exactly what was parsed, including comments, whitespace, and the author's choice of quoting.

    Document::walk

    fn Document::walk(self : Document, visit : (Cursor) -> Unit) -> Unit

    Visit every node in the document in document order, the document node excluded.

    The walk is a flat scan over node ids: it does not recurse, so depth is bounded by the tree rather than by the stack, and it builds no intermediate array.

    test "walk counts nodes by kind" {
    let doc = @xml.parse("<r>t<!--c--><a/></r>")
    let kinds : Array[@xml.NodeKind] = []
    doc.walk(fn(cursor) { kinds.push(cursor.kind()) })
    assert_eq(kinds.length(), 4)
    assert_eq(kinds[0], @xml.NodeKind::Element)
    assert_eq(kinds[1], @xml.NodeKind::Text)
    assert_eq(kinds[2], @xml.NodeKind::Comment)
    assert_eq(kinds[3], @xml.NodeKind::Element)
    }

    Element

    pub struct Element {
    // private fields
    }

    An element node.

    Reading a name, an attribute, or the text allocates only what was asked for and caches it on the document, so asking twice decodes once.
    impl Eq for Element

    Element::all

    fn Element::all(self : Element, query : String) -> Array[Element]

    Every descendant element whose name matches query, in document order.

    The element itself is not included, even when it matches.

    Element::attr_namespace_uri

    fn Element::attr_namespace_uri(self : Element, name : String) -> String?

    The namespace URI of one of the element's attributes, or None.

    Unprefixed attributes are in no namespace, as XML requires: a default declaration does not apply to them, so attr_namespace_uri("id") is None even inside a document whose default namespace is set.

    test "attributes need an explicit prefix" {
    let doc = @xml.parse(
    "<r xmlns=\"urn:d\" xmlns:q=\"urn:q\" q:id=\"1\" id=\"2\"/>",
    )
    let r = doc.root().unwrap()
    assert_eq(r.attr_namespace_uri("q:id"), Some("urn:q"))
    assert_eq(r.attr_namespace_uri("id"), None)
    }

    Element::attributes

    fn Element::attributes(self : Element) -> Attributes

    The element's attributes as a read-only view.

    The first call scans the start tag and caches the pairs on the document; later calls return the same view. Attributes::to_map is the one operation that copies.

    Element::children

    fn Element::children(self : Element) -> Array[Node]

    The element's direct children: text, elements, comments, CDATA, and processing instructions, in source order.

    The array is built on each call and holds handles, so it costs one slot per child. elements is the filtered version, and walk visits the whole subtree without building either.

    Element::cursor

    fn Element::cursor(self : Element) -> Cursor

    A cursor at this element.

    Useful for mixing the element API with cursor navigation, for example to keep walking from a node that was found by name.

    Element::elements

    fn Element::elements(self : Element) -> Array[Element]

    The element's direct child elements, skipping text and the rest.

    Whitespace-only text between elements is still a text node, so this is usually what a caller wants instead of filtering children by hand.

    Element::end

    fn Element::end(self : Element) -> Int

    The offset just past the > that closes the element.

    For <a/> this is the end of the tag itself, so end - start is the length of the markup and stringify reproduces it exactly.

    Element::find

    fn Element::find(self : Element, query : String) -> Element?

    The first descendant element whose name matches query.

    Descendants only: the element itself is never returned. Matching follows Document::find, qualified name or local part, case-sensitive.

    Element::get_attr

    fn Element::get_attr(self : Element, name : String) -> String?

    The value of one attribute, matched exactly, or None.

    The name is compared as written: case-sensitive, prefix included, and not resolved through namespaces, so get_attr("id") does not find q:id. The value is entity-decoded.

    Element::has_attr

    fn Element::has_attr(self : Element, name : String) -> Bool

    Whether the attribute is present, matched exactly.

    The same matching rules as get_attr, for callers that only care about presence.

    Element::inner

    fn Element::inner(self : Element) -> String

    The raw source between this element's open and close tags.

    Nothing is decoded or re-serialized: this is a slice of the source, so &amp; stays &amp; and <b/> stays <b/>. text is the decoded alternative.

    Element::is_empty_element

    fn Element::is_empty_element(self : Element) -> Bool

    Whether the element was written as <name/>.

    This is a fact about the source, not about the content: <a></a> and <a/> both have no children, and only the second reports true.

    Element::local_name

    fn Element::local_name(self : Element) -> String

    The local part of the name, without any prefix.

    Both p:item and item have local name item. Only the first colon separates the prefix, so a name with more than one keeps the rest.

    Element::name

    fn Element::name(self : Element) -> String

    The element's qualified name, with its namespace prefix if it has one.

    The name is interned at parse time, so this is a table lookup rather than a copy of the source.

    Element::namespace_uri

    fn Element::namespace_uri(self : Element) -> String?

    The namespace URI the element's prefix is bound to, or None.

    An unprefixed element resolves through the default namespace; when no declaration is in scope it has no namespace. xmlns="" unbinds the default namespace and yields None. The xml prefix is bound to http://www.w3.org/XML/1998/namespace without a declaration, as the spec requires.

    Resolution is lazy: the bindings in scope are collected and cached the first time an element is asked, so a parse that never asks costs nothing.

    test "resolve namespaces" {
    let doc = @xml.parse("<r xmlns=\"urn:d\" xmlns:p=\"urn:p\"><p:i/><j/></r>")
    let p = doc.find("i").unwrap()
    assert_eq(p.prefix(), "p")
    assert_eq(p.namespace_uri(), Some("urn:p"))
    assert_eq(doc.find("j").unwrap().namespace_uri(), Some("urn:d"))
    }

    Element::prefix

    fn Element::prefix(self : Element) -> String

    The namespace prefix, or "" when the name is unprefixed.

    p:item has prefix p, and item has prefix "". This is the prefix the name was written with, not what the declaration binds it to; resolving it is namespace_uri's job.

    Element::start

    fn Element::start(self : Element) -> Int

    The offset of the < that opens the element.

    Element::stringify

    fn Element::stringify(self : Element) -> String

    The element's source text, from < to the end of its close tag.

    Because the tree stores offsets, this is a slice of the original source and reproduces the authored markup exactly, nested nodes included.

    Element::text

    fn Element::text(self : Element) -> String

    The decoded text of all descendant text and CDATA nodes, concatenated.

    Element boundaries contribute nothing, so <a>x<b>y</b>z</a> has the text xyz. CDATA content is appended verbatim, which is what the section means and why a reference written inside one is not expanded. The result is built on first read and cached on the document.

    test "text concatenates across descendants" {
    let doc = @xml.parse("<a>x<b>y</b>z<![CDATA[&amp;]]></a>")
    assert_eq(doc.root().unwrap().text(), "xyz&amp;")
    }

    Element::walk

    fn Element::walk(self : Element, visit : (Cursor) -> Unit) -> Unit

    Visit every descendant of this element, the element itself excluded.

    The walk is a flat scan over ids: it does not recurse, so 2000 levels of nesting are walked in a loop rather than on the stack.

    Node

    pub(all) enum Node {
    Element(Element)
    Text(Text)
    CData(CData)
    Comment(Comment)
    PI(PI)
    DocType(DocType)
    } derive(Eq,
    Debug
    )

    Any node in the tree, as returned by Document::children and Element::children.

    Node is an enum of handles, so matching on it is how a caller distinguishes the kinds without asking Cursor::kind first, and without losing the typed accessors each variant carries.

    Node::end

    fn Node::end(self : Node) -> Int

    The offset where the node ends, whatever its kind.

    Node::start

    fn Node::start(self : Node) -> Int

    The offset where the node starts, whatever its kind.

    For a text node this is its first character; for the marked-up kinds it is the < of the construct.

    Node::stringify

    fn Node::stringify(self : Node) -> String

    The node's source text, whatever its kind.

    A slice of the original source, so a node round-trips exactly and nested nodes come along with it.

    NodeKind

    pub(all) enum NodeKind {
    Document
    Element
    Text
    CData
    Comment
    PI
    DocType
    } derive(Eq,
    Debug
    )

    The kind of a node, as reported by Cursor::kind.

    Document is the position Document::cursor starts at, and the other variants correspond one to one with the variants of Node. Comparing kinds is how a flat walk decides what to do with a cursor without matching on a node value.
    pub struct PI {
    // private fields
    }

    A processing instruction, including the XML declaration.

    <?xml version="1.0"?> is a PI whose target is xml and whose data is version="1.0"; the declaration is not special-cased beyond that.
    impl Eq for PI
    impl Debug for PI

    PI::data

    fn PI::data(self : PI) -> String

    The data of a processing instruction, without the leading whitespace.

    For <?xml version="1.0"?> the data is version="1.0"; for <?pi?> it is the empty string.

    PI::end

    fn PI::end(self : PI) -> Int

    The offset just past the > in ?>.

    PI::start

    fn PI::start(self : PI) -> Int

    The offset of the < in <?.

    The range covers the whole instruction, <? and ?> included.

    PI::target

    fn PI::target(self : PI) -> String

    The target of a processing instruction, e.g. xml for the declaration.

    The target is the name immediately after <?, before any whitespace.

    Parent

    pub(all) enum Parent {
    Document(Document)
    Element(Element)
    } derive(Eq,
    Debug
    )

    The parent of a node: the document itself, or an element.

    Cursor::parent reports a position rather than a Parent, so this is the typed form for callers that want to match on which of the two it is.

    Position

    pub(all) struct Position {
    line : Int
    column : Int
    } derive(Eq,
    Debug
    )

    A one-based line and column, counted in UTF-16 code units.

    Document::position converts a source offset into this. Columns count code units rather than characters, so a character outside the BMP advances the column by two, matching the offsets the rest of this API reports.

    Text

    pub struct Text {
    // private fields
    }

    A text node.

    The source is kept as written: Text::value decodes entity and character references, Text::raw does not. A run of text between two tags is one node, even when it contains references.
    impl Eq for Text

    Text::end

    fn Text::end(self : Text) -> Int

    The offset just past the text node's last code unit.

    Text::raw

    fn Text::raw(self : Text) -> String

    The raw content of a text node, before entity decoding.

    A slice of the source, so it is what the author wrote, references and all.

    Text::start

    fn Text::start(self : Text) -> Int

    The offset of the text node's first code unit.

    Unlike the marked-up nodes, a text node's range covers its content only; there are no delimiters to include.

    Text::value

    fn Text::value(self : Text) -> String

    The decoded text of a text node.

    Entity and character references are replaced, and the result is cached on the document, so reading the same node twice decodes once. raw returns the source instead.

    test "text decodes and raw does not" {
    let doc = @xml.parse("<a>x &amp; &#65;</a>")
    let text = match doc.root().unwrap().children()[0] {
    @xml.Node::Text(text) => text
    _ => abort("expected a text node")
    }
    assert_eq(text.value(), "x & A")
    assert_eq(text.raw(), "x &amp; &#65;")
    }

    parse

    fn parse(source : String) -> Document

    Parse an XML document.

    The parser never fails: markup it cannot make sense of is recorded in Document::error and parsing continues from the next <. Every node keeps its source offsets, so the document round-trips by slicing the original string.

    Parsing is one pass over source, and the tree is allocated in proportion to the number of nodes rather than to the number of bytes. Nothing is decoded until it is read.

    test "parse recovers instead of throwing" {
    let doc = @xml.parse("<a><b></a>")
    assert_false(doc.is_well_formed())
    assert_eq(doc.error(), Some(6))
    assert_eq(doc.position(6), { line: 1, column: 7, })
    }

    Source Files