Xml

:= { declaration : Try(Declaration, [Missing]), root : Node }

XML documents, readers and resolved namespace values.

parse_str : Str, Props -> Try(Xml, ReadError)

Parse complete XML with explicit resource limits.

parser : {} -> Parser(Bytes, Xml, Problem)

Construct an XML parser for composition.

validate : ValidationProps -> Try(Xml, [InvalidXml(Error)])

Check source with quotation lint rules using typed native diagnostics.

Namespaced

:= { declaration : Try(Declaration, [Missing]), root : Node }

XML documents with namespace-resolved names.

encode : Namespaced, WriteProps -> Try(List(U8), [Unrenderable(Diagnostic(EncodeProblem))])

Node

:= [
    Element({ name : Name, bindings : List(Binding), attributes : List(Attribute), children : List(Node) }),
    Text(Str),
]
is_eq : _

Compare two nodes structurally.

to_hash : _

Hash a node, so nodes can be Dict keys and Set members.

name : Node -> Try(Name, [NotAnElement])

The resolved name of an element, or Err(NotAnElement) for text.

attribute : Node, Namespace, Str -> Try(Str, [Missing])

The value of the element's attribute with this namespace and local name, or Err(Missing) when there is none or the node is text.

expect {
    root = Xml.Namespaced.parse_str("<a xmlns:x='urn:x' x:id='1' id='2'/>", {})?.root
    root.attribute(Uri("urn:x"), "id") == Ok("1") and root.attribute(NoNamespace, "id") == Ok("2")
}
children_named : Node, Namespace, Str -> List(Node)

The element's direct child elements with this namespace and local name, in document order. Empty for a text node.

text : Node -> Str

All character data in the node and its descendants, concatenated in document order.

Reader

Xml.Namespaced.Reader :: # (opaque)

A pull reader that resolves namespaces as it reads, as Xml.Reader does for names as written. Keep only the latest reader and return from the loop's Done arm.

next : Reader -> [Event(Event, Reader), Done, Failed(ReadError)]

The next event, Done at the end of the document, or Failed.

element : Reader -> [Element(Node, Reader), Failed(ReadError), NotAfterStart]

Directly after a Start event, that element and its subtree, and the reader after its end tag. NotAfterStart otherwise.

metadata : Reader -> Metadata

Original position and declaration of this pull reader.

WriteProps

:= {
    declaration : [Plain, Standalone, Omitted] ?? Plain,
    prefixes : [AsRead, Table(List({ prefix : Str, namespace : Str }))] ?? AsRead,
    attribute_order : AttributeOrder ?? AsGiven,
}

How Xml.Namespaced.encode writes a document.

  • declaration: Plain writes <?xml version="1.0" encoding="UTF-8"?> and a line feed, Standalone also declares standalone="yes", and Omitted writes no declaration.
  • prefixes: AsRead writes each element's own bindings and each name's own prefix. Table(entries) writes each name with its namespace's prefix from the table, ignoring the tree's prefixes and bindings, and declares on the root, in table order, every namespace the document uses. An empty prefix makes a namespace the default for elements, declared with xmlns="u" on the first element that needs it (the root, when it is in that namespace), and xmlns="" or xmlns="u" is written wherever the default must change. The xml namespace is always written with xml.
  • attribute_order: AsGiven keeps each element's attributes in order, and SortedBy(compare) sorts them.

Lints

:= { non_utf8_declaration : Bool ?? True }

Optional checks for suspicious XML that is otherwise well formed.

ValidationProps

:= { source : Str, name : Str ?? "<literal>", lints : Lints ?? {} }

Checked source and enabled lint rules. A source name appears in errors.

Node

:= [
    Element({ name : Str, attributes : List(Attribute), children : List(Node) }),
    Text(Str),
]
is_eq : _

Compare two XML nodes structurally.

to_hash : _

Hash an XML node, so nodes can be Dict keys and Set members.

name : Node -> Try(Str, [NotAnElement])

The name of an element, or Err(NotAnElement) for a text node.

expect Xml.parse_str("<svg:rect/>", {}).map_ok(|xml| xml.root.name()) == Ok(Ok("svg:rect"))
attribute : Node, Str -> Try(Str, [Missing])

The value of the element's attribute with this exact name, or Err(Missing) when there is none or the node is text.

expect {
    root = Xml.parse_str("<a href='/x'/>", {})?.root
    root.attribute("href") == Ok("/x") and root.attribute("title") == Err(Missing)
}
children_named : Node, Str -> List(Node)

The element's direct child elements with this exact name, in document order. Empty for a text node.

expect {
    root = Xml.parse_str("<list><item>1</item><other/><item>2</item></list>", {})?.root
    root.children_named("item").map(|item| item.text()) == ["1", "2"]
}
text : Node -> Str

All character data in the node and its descendants, concatenated in document order (like the DOM's textContent).

expect Xml.parse_str("<p>Hello, <b>world</b>!</p>", {}).map_ok(|xml| xml.root.text()) == Ok("Hello, world!")

ReaderProps

:= { max_depth : U64 ?? 1024, max_elements : U64 ?? 4_194_304, max_attributes : U64 ?? 1024, namespaces : Bool ?? False }

Limits for untrusted input, checked while reading.

A document deeper than max_depth elements, with more than max_elements elements, or with an element that has more than max_attributes attributes fails with LimitExceeded. The defaults admit large real documents: at about 28 bytes per element, 4,194,304 elements is a 117 MB document.

namespaces also rejects processing instruction targets that contain a colon, as Namespaces in XML 1.0 requires. Xml.Namespaced sets it; names are still reported as written.

Props

:= { limits : [Unbounded, Bounded(ReaderProps)] ?? Unbounded }

Complete XML parsing preserves the source-bounded default; explicit limits are opt-in.

StreamProps

:= { max_depth : U64 ?? 1024, max_elements : U64 ?? 4_194_304, max_attributes : U64 ?? 1024, max_token_bytes : U64 ?? 65_536, max_text_bytes : U64 ?? 65_536, max_context_bytes : U64 ?? 4_194_304, namespaces : Bool ?? False, errors : RecoveryProps ?? {} }

Bounds for chunked XML. Tokens include complete tags, comments, and PIs. Text and CDATA may be split into multiple Text events, independently of input chunk boundaries. The decoder accepts UTF-8 bytes only.

Reader

Xml.Reader :: # (opaque)

A pull reader over one document, for reading a large document an element at a time without building its whole tree.

Get one with Xml.reader, then call next until it returns Done. element, called directly after a Start, builds that element's subtree and continues after its end tag. A reader is a plain value: keep only the latest one, and return from the loop's Done arm, so each step updates the reader's stack of open elements in place.

expect {
    count_items = |reader| {
        var $reader = reader
        var $count = 0
        while True {
            match $reader.next() {
                Event(Start({ name: "item", .. }), rest) => {
                    $reader = rest
                    $count = $count + 1
                }

                Event(_, rest) => {
                    $reader = rest
                }

                Done => return Ok($count)
                Failed(error) => return Err(error)
            }
        }
    }
    count_items(Xml.reader("<list><item/><item>x</item></list>", {})?) == Ok(2)
}
next : Reader -> [Event(Event, Reader), Done, Failed(ReadError)]

The next event, Done once the root element has ended and the rest of the input is only comments, processing instructions and whitespace, or Failed at the first problem.

expect {
    reader = Xml.reader("<a>x</a>", {})?
    match reader.next() {
        Event(Start({ name, .. }), rest) =>
            match rest.next() {
                Event(Text(text), _) => name == "a" and text == "x"
                _ => False
            }

        _ => False
    }
}
element : Reader -> [Element(Node, Reader), Failed(ReadError), NotAfterStart]

Directly after a Start event, that element and its subtree, and the reader after its end tag. NotAfterStart when the most recent event was not a Start.

expect {
    reader = Xml.reader("<doc><p>one</p><p>two</p></doc>", {})?
    match reader.next() {
        Event(Start(_), after_doc) =>
            match after_doc.next() {
                Event(Start(_), after_p) =>
                    match after_p.element() {
                        Element(p, _) => p.text() == "one"
                        _ => False
                    }

                _ => False
            }

        _ => False
    }
}
element_with : Reader, { context : ctx, first : open, start : ctx, Str, List(Attribute) -> Try({ context : ctx, open : open }, err), text : Str -> node, end : ctx, open, List(node) -> { context : ctx, node : node } } -> [Element(node, ctx, Reader), Failed(ReadError), Rejected(err, Location), NotAfterStart]

Directly after a Start event, builds that element's subtree as your own type, as element builds an Xml.Node, and returns the reader after its end tag. Use it to build a model of the document without an Xml.Node tree beside it.

first stands for the element whose Start was just read. Each element inside it is passed to start with its name and attributes, which may fail with your own error; text makes a node of text; and end makes an element's node from what start (or first) gave and its children. context is threaded through start and end in document order. A failure of start is Rejected with the location of that start tag.

expect {
    reader = Xml.reader("<doc><p>one</p><p>two<b/></p></doc>", {})?
    match reader.next() {
        Event(Start(_), rest) =>
            match rest.element_with({ context: 0, first: "doc", start: |count, name, _| Ok({ context: count + 1, open: name }), text: |text| text, end: |count, name, children| { context: count, node: "${name}(${Str.join_with(children, ",")})" } }) {
                Element(tree, count, _) => tree == "doc(p(one),p(two,b()))" and count == 3
                _ => False
            }

        _ => False
    }
}
metadata : Reader -> Metadata

Original position and declaration of this pull reader.