use std::fmt;
pub const XML_NS: &str = "{http://www.w3.org/XML/1998/namespace}";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EtreeError(pub String);
impl fmt::Display for EtreeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for EtreeError {}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Element {
pub tag: String,
pub attrib: Vec<(String, String)>,
pub text: Option<String>,
pub children: Vec<Element>,
pub tail: Option<String>,
}
impl Element {
pub fn new(tag: impl Into<String>) -> Self {
Element {
tag: tag.into(),
..Default::default()
}
}
pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) {
let key = key.into();
let value = value.into();
match self.attrib.iter_mut().find(|(k, _)| *k == key) {
Some(slot) => slot.1 = value,
None => self.attrib.push((key, value)),
}
}
pub fn get(&self, key: &str) -> Option<&str> {
self.attrib
.iter()
.find(|(k, _)| k == key)
.map(|(_, v)| v.as_str())
}
pub fn append(&mut self, child: Element) {
self.children.push(child);
}
pub fn len(&self) -> usize {
self.children.len()
}
pub fn is_empty(&self) -> bool {
self.children.is_empty()
}
}
fn check_xml_string(s: &str) -> Result<(), EtreeError> {
let ok = s.chars().all(|c| {
matches!(c, '\t' | '\n' | '\r')
|| ('\u{20}'..='\u{D7FF}').contains(&c)
|| ('\u{E000}'..='\u{FFFD}').contains(&c)
|| c >= '\u{10000}'
});
if ok {
Ok(())
} else {
Err(EtreeError(
"All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters"
.into(),
))
}
}
fn qname(name: &str) -> Result<String, EtreeError> {
if let Some(local) = name.strip_prefix(XML_NS) {
return Ok(format!("xml:{local}"));
}
if name.is_empty() || name.starts_with('{') || name.contains(['<', '>', '&', '"', ' ']) {
return Err(EtreeError(format!("Invalid tag name {name:?}")));
}
Ok(name.to_owned())
}
fn push_text(out: &mut String, text: &str) {
for c in text.chars() {
match c {
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'&' => out.push_str("&"),
'\r' => out.push_str(" "),
_ => out.push(c),
}
}
}
fn push_attr_value(out: &mut String, value: &str) {
for c in value.chars() {
match c {
'"' => out.push_str("""),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'&' => out.push_str("&"),
'\n' => out.push_str(" "),
'\r' => out.push_str(" "),
'\t' => out.push_str("	"),
_ => out.push(c),
}
}
}
fn write_element(
out: &mut String,
element: &Element,
level: usize,
pretty: bool,
) -> Result<(), EtreeError> {
let indent = |out: &mut String, level: usize| {
for _ in 0..level.min(30) {
out.push_str(" ");
}
};
let tag = qname(&element.tag)?;
out.push('<');
out.push_str(&tag);
for (key, value) in &element.attrib {
check_xml_string(value)?;
out.push(' ');
out.push_str(&qname(key)?);
out.push_str("=\"");
push_attr_value(out, value);
out.push('"');
}
if element.text.is_none() && element.children.is_empty() {
out.push_str("/>");
return Ok(());
}
out.push('>');
let format =
pretty && element.text.is_none() && element.children.iter().all(|c| c.tail.is_none());
if let Some(text) = &element.text {
check_xml_string(text)?;
push_text(out, text);
}
if format {
out.push('\n');
}
for child in &element.children {
if format {
indent(out, level + 1);
}
write_element(out, child, level + 1, format)?;
if let Some(tail) = &child.tail {
check_xml_string(tail)?;
push_text(out, tail);
}
if format {
out.push('\n');
}
}
if format {
indent(out, level);
}
out.push_str("</");
out.push_str(&tag);
out.push('>');
Ok(())
}
pub fn tostring(
root: &Element,
pretty_print: bool,
xml_declaration: bool,
) -> Result<String, EtreeError> {
let mut out = String::new();
if xml_declaration {
out.push_str("<?xml version='1.0' encoding='UTF-8'?>\n");
}
write_element(&mut out, root, 0, pretty_print)?;
if pretty_print {
out.push('\n');
}
Ok(out)
}
fn clark(namespace: Option<&str>, name: &str) -> String {
match namespace {
Some(ns) => format!("{{{ns}}}{name}"),
None => name.to_owned(),
}
}
fn convert(node: roxmltree::Node<'_, '_>) -> Result<Element, EtreeError> {
let tag = node.tag_name();
let mut element = Element::new(clark(tag.namespace(), tag.name()));
element.attrib = node
.attributes()
.map(|a| (clark(a.namespace(), a.name()), a.value().to_owned()))
.collect();
for child in node.children() {
if child.is_element() {
element.children.push(convert(child)?);
} else if child.is_text() {
let text = child.text().unwrap_or_default();
let slot = match element.children.last_mut() {
Some(last) => &mut last.tail,
None => &mut element.text,
};
slot.get_or_insert_with(String::new).push_str(text);
} else {
return Err(EtreeError(
"comments and processing instructions are not supported".into(),
));
}
}
Ok(element)
}
pub fn fromstring(text: &str) -> Result<Element, EtreeError> {
let options = roxmltree::ParsingOptions {
allow_dtd: true,
..Default::default()
};
let doc = roxmltree::Document::parse_with_options(text, options)
.map_err(|e| EtreeError(e.to_string()))?;
convert(doc.root_element())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lxml_pretty_print() -> Result<(), EtreeError> {
let mut root = Element::new("a");
let mut s = Element::new("string");
s.text = Some(String::new());
root.append(s);
let mut t = Element::new("t");
t.text = Some("x<>&\"\r\n\t".into());
t.set(format!("{XML_NS}lang"), "a\"<>&\n\r\t'");
root.append(t);
let mut e = Element::new("e");
e.append(Element::new("x"));
root.append(e);
assert_eq!(
tostring(&root, true, true)?,
"<?xml version='1.0' encoding='UTF-8'?>\n<a>\n <string></string>\n <t xml:lang=\"a"<>& 	'\">x<>&\" \n\t</t>\n <e>\n <x/>\n </e>\n</a>\n"
);
Ok(())
}
#[test]
fn rejects_control_characters() {
let mut root = Element::new("a");
root.text = Some("\u{1}".into());
assert!(tostring(&root, true, true).is_err());
}
}