Skip to content

xml

Read and write XML documents. A document is a tree of Elements; each holds its name, its attributes in order, and its children, which are elements and text (Node.Element, Node.Text).

import xml
let feed = try xml.parse(&"<feed lang=\"en\">\n <title>News &amp; more</title>\n <item id=\"1\">First</item>\n <item id=\"2\"><![CDATA[<b>Second</b>]]></item>\n</feed>")
print(feed.attr(&"lang"))
print(feed.child(&"title").unwrap().text())
for item in feed.children_named(&"item") {
print(f"{item.attr(&"id").unwrap()}: {item.text()}")
}
Some("en")
News & more
1: First
2: <b>Second</b>

text() gives all the text inside an element, with entities decoded and CDATA as written. child finds the first child element with a name, children_named all of them, and elements every child element.

import xml
let mut note = xml.element(&"note")
note.set_attr(&"to", &"Ada & Grace")
let mut body = xml.element(&"body")
body.add_text(&"1 < 2, as always")
note.add(body)
note.add(xml.element(&"signed"))
print(note)
print(xml.pretty(&note))
<note to="Ada &amp; Grace"><body>1 &lt; 2, as always</body><signed/></note>
<?xml version="1.0" encoding="UTF-8"?>
<note to="Ada &amp; Grace">
<body>1 &lt; 2, as always</body>
<signed/>
</note>

to_str() (also what print and f-strings show) writes compact XML; pretty writes a whole file: the XML declaration, two spaces per level, and a final line break. Everything is escaped as needed, so the output always parses back to the same tree.

A document with a <!DOCTYPE ...> is refused. A DTD can define entities that expand to gigabytes (“billion laughs”) or read local files and URLs (XXE), so Brass does not read DTDs at all, and there is no switch to turn that on.

import xml
let attack = "<?xml version=\"1.0\"?>\n<!DOCTYPE lolz [<!ENTITY lol \"lol\"><!ENTITY lol2 \"&lol;&lol;&lol;\">]>\n<lolz>&lol2;</lolz>"
let doc = xml.parse(&attack) catch |e| {
print(f"line {e.line}: {e.message}")
xml.element(&"empty")
}
print(doc.name)
line 2: DOCTYPE is not supported (it enables entity-expansion and external-entity attacks)
empty

Other errors, each with its line: tags that do not match or are never closed, a second root or text after the root, unknown entities, duplicate attributes, < inside an attribute value, an encoding other than UTF-8, bytes that are not valid UTF-8, and elements nested more than 256 levels deep.

import xml
pub fn parse(text: &Str) -> Element ! XmlError

The root element of a well-formed XML 1.0 document; DOCTYPE and custom entities are refused.

Comments and processing instructions are skipped, and line endings become \n. Text that is only white space between elements is kept as text nodes, so mixed content such as <p>a <b>bold</b> word</p> comes back exactly. Use strip_space to drop that indentation when comparing trees. Namespace prefixes stay part of the name (soap:Envelope); xmlns attributes are ordinary attributes.

pub fn element(name: &Str) -> Element

An empty element to build on with add, add_text and set_attr.

pub fn escape(text: &Str) -> Str

& < > " ' become entities, so the text is safe anywhere in a document.

For writing XML by hand: replaces &, <, >, " and ' with entities.

pub fn pretty(e: &Element) -> Str

A full document file: the UTF-8 declaration, then two spaces per level; mixed content stays inline.

pub struct XmlError {
pub line: i64
pub message: Str
}
pub enum Node {
Element(Element)
Text(Str)
}
pub struct Element {
pub name: Str
pub attributes: Vec<(Str, Str)>
pub children: Vec<Node>
}

An element; namespace prefixes stay part of the name (soap:Envelope), xmlns is an attribute.

pub fn attr(&self, name: &Str) -> Option<Str>
pub fn set_attr(&mut self, name: &Str, value: &Str)

Replaces the value of an existing attribute in place, or adds it at the end.

pub fn child(&self, name: &Str) -> Option<&Element>

The first child element called name.

pub fn children_named(&self, name: &Str) -> Vec<&Element>
pub fn elements(&self) -> Vec<&Element>

The child elements, skipping text.

pub fn text(&self) -> Str

All text inside, at any depth, in document order.

pub fn add(&mut self, child: Element)
pub fn add_text(&mut self, text: &Str)

Text next to other text joins it, as it would after writing and reading back.

pub fn strip_space(&self) -> Element

A copy without the blank text between child elements that pretty leaves out.

A copy without the white-space-only text between child elements, as indentation leaves it. After pretty, xml.parse(&text).strip_space() equals the original tree’s strip_space().

pub fn to_str(&self) -> Str

Compact XML with no declaration and no added space.