///|
/// A parsed XML/SVG document: a sequence of top level nodes, usually a
/// prolog (``, doctype, comments) followed by one root element.
#derive(Debug)
pub(all) struct Document {
children : Array[Node]
}
///|
pub extend Document with Debug::{to_repr}
///|
/// One node of the tree. Text is stored decoded (entities resolved);
/// comments, CDATA, doctype and processing instructions keep their raw body.
#derive(Debug)
pub(all) enum Node {
Element(Element)
Text(String)
Comment(String)
CData(String)
Doctype(String)
/// processing instruction: target and data (``)
ProcInst(String, String)
}
///|
pub extend Node with Debug::{to_repr}
///|
/// An element with its tag name, attributes and child nodes. Plugins mutate
/// elements in place; `name` is mutable so shapes can be turned into paths.
#derive(Debug)
pub(all) struct Element {
mut name : String
/// attributes in source order; MoonBit maps preserve insertion order
attrs : Map[String, String]
children : Array[Node]
}
///|
pub extend Element with Debug::{to_repr}
///|
/// Create an element; attributes and children default to empty.
pub fn Element::new(
name : String,
attrs~ : Map[String, String] = Map([]),
children~ : Array[Node] = [],
) -> Element {
{ name, attrs, children, }
}
///|
/// Attribute value by name.
pub fn Element::get(self : Element, name : String) -> String? {
self.attrs.get(name)
}
///|
/// Set (or append) an attribute.
pub fn Element::set(self : Element, name : String, value : String) -> Unit {
self.attrs[name] = value
}
///|
/// Remove an attribute if present.
pub fn Element::remove(self : Element, name : String) -> Unit {
self.attrs.remove(name)
}
///|
/// Whether the attribute is present.
pub fn Element::has(self : Element, name : String) -> Bool {
self.attrs.contains(name)
}
///|
/// Child elements only (skipping text and comments).
pub fn Element::elements(self : Element) -> Array[Element] {
let out = []
for c in self.children {
if c is Element(e) {
out.push(e)
}
}
out
}
///|
/// The root `