Skip to content

xml

The xml module provides XML parsing and serialization. XML documents are represented as nested HashMap nodes with a consistent structure.

use std::core::xml

Each XML element is represented as a HashMap with these fields:

FieldTypeDescription
namestringElement tag name
attributesHashMap<string, string>Element attributes
childrenArray<HashMap>Child element nodes
textstring?Text content (present only if element has text)

xml::parse(text: string) -> Result<HashMap, string>

Section titled “xml::parse(text: string) -> Result<HashMap, string>”

Parse an XML string into a node HashMap. The result is the root element. XML declarations, comments, and processing instructions are skipped.

let doc = xml::parse("""
<config>
<db host="localhost" port="5432"/>
<app>my-service</app>
</config>
""")?
print(doc["name"]) // "config"
print(doc["children"].length) // 2
let app = doc["children"][1]
print(app["text"]) // "my-service"

Attributes are accessible from the attributes field:

let doc = xml::parse("""<person name="Alice" age="30">hello</person>""")?
print(doc["attributes"]["name"]) // "Alice"
print(doc["text"]) // "hello"

Self-closing elements (e.g., <br/>) are parsed as nodes with an empty children array and no text field.

xml::stringify(value: HashMap) -> Result<string, string>

Section titled “xml::stringify(value: HashMap) -> Result<string, string>”

Serialize a node HashMap back to an XML string. The node must have at minimum a name field. Elements with no children and no text are written as self-closing tags.

let xml_str = xml::stringify({
name: "root",
attributes: { version: "1.0" },
children: [
{ name: "item", attributes: { id: "1" }, children: [], text: "hello" }
]
})?
// <root version="1.0"><item id="1">hello</item></root>
  • json — JSON parsing and serialization