1use std::fmt;
12
13pub const XML_NS: &str = "{http://www.w3.org/XML/1998/namespace}";
15
16#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct EtreeError(pub String);
19
20impl fmt::Display for EtreeError {
21 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22 f.write_str(&self.0)
23 }
24}
25
26impl std::error::Error for EtreeError {}
27
28#[derive(Debug, Clone, PartialEq, Default)]
30pub struct Element {
31 pub tag: String,
33 pub attrib: Vec<(String, String)>,
35 pub text: Option<String>,
37 pub children: Vec<Element>,
39 pub tail: Option<String>,
41}
42
43impl Element {
44 pub fn new(tag: impl Into<String>) -> Self {
46 Element {
47 tag: tag.into(),
48 ..Default::default()
49 }
50 }
51
52 pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) {
54 let key = key.into();
55 let value = value.into();
56 match self.attrib.iter_mut().find(|(k, _)| *k == key) {
57 Some(slot) => slot.1 = value,
58 None => self.attrib.push((key, value)),
59 }
60 }
61
62 pub fn get(&self, key: &str) -> Option<&str> {
64 self.attrib
65 .iter()
66 .find(|(k, _)| k == key)
67 .map(|(_, v)| v.as_str())
68 }
69
70 pub fn append(&mut self, child: Element) {
72 self.children.push(child);
73 }
74
75 pub fn len(&self) -> usize {
77 self.children.len()
78 }
79
80 pub fn is_empty(&self) -> bool {
82 self.children.is_empty()
83 }
84}
85
86fn check_xml_string(s: &str) -> Result<(), EtreeError> {
89 let ok = s.chars().all(|c| {
90 matches!(c, '\t' | '\n' | '\r')
91 || ('\u{20}'..='\u{D7FF}').contains(&c)
92 || ('\u{E000}'..='\u{FFFD}').contains(&c)
93 || c >= '\u{10000}'
94 });
95 if ok {
96 Ok(())
97 } else {
98 Err(EtreeError(
99 "All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters"
100 .into(),
101 ))
102 }
103}
104
105fn qname(name: &str) -> Result<String, EtreeError> {
108 if let Some(local) = name.strip_prefix(XML_NS) {
109 return Ok(format!("xml:{local}"));
110 }
111 if name.is_empty() || name.starts_with('{') || name.contains(['<', '>', '&', '"', ' ']) {
112 return Err(EtreeError(format!("Invalid tag name {name:?}")));
113 }
114 Ok(name.to_owned())
115}
116
117fn push_text(out: &mut String, text: &str) {
119 for c in text.chars() {
120 match c {
121 '<' => out.push_str("<"),
122 '>' => out.push_str(">"),
123 '&' => out.push_str("&"),
124 '\r' => out.push_str(" "),
125 _ => out.push(c),
126 }
127 }
128}
129
130fn push_attr_value(out: &mut String, value: &str) {
132 for c in value.chars() {
133 match c {
134 '"' => out.push_str("""),
135 '<' => out.push_str("<"),
136 '>' => out.push_str(">"),
137 '&' => out.push_str("&"),
138 '\n' => out.push_str(" "),
139 '\r' => out.push_str(" "),
140 '\t' => out.push_str("	"),
141 _ => out.push(c),
142 }
143 }
144}
145
146fn write_element(
147 out: &mut String,
148 element: &Element,
149 level: usize,
150 pretty: bool,
151) -> Result<(), EtreeError> {
152 let indent = |out: &mut String, level: usize| {
154 for _ in 0..level.min(30) {
155 out.push_str(" ");
156 }
157 };
158 let tag = qname(&element.tag)?;
159 out.push('<');
160 out.push_str(&tag);
161 for (key, value) in &element.attrib {
162 check_xml_string(value)?;
163 out.push(' ');
164 out.push_str(&qname(key)?);
165 out.push_str("=\"");
166 push_attr_value(out, value);
167 out.push('"');
168 }
169 if element.text.is_none() && element.children.is_empty() {
170 out.push_str("/>");
171 return Ok(());
172 }
173 out.push('>');
174 let format =
176 pretty && element.text.is_none() && element.children.iter().all(|c| c.tail.is_none());
177 if let Some(text) = &element.text {
178 check_xml_string(text)?;
179 push_text(out, text);
180 }
181 if format {
182 out.push('\n');
183 }
184 for child in &element.children {
185 if format {
186 indent(out, level + 1);
187 }
188 write_element(out, child, level + 1, format)?;
189 if let Some(tail) = &child.tail {
190 check_xml_string(tail)?;
191 push_text(out, tail);
192 }
193 if format {
194 out.push('\n');
195 }
196 }
197 if format {
198 indent(out, level);
199 }
200 out.push_str("</");
201 out.push_str(&tag);
202 out.push('>');
203 Ok(())
204}
205
206pub fn tostring(
209 root: &Element,
210 pretty_print: bool,
211 xml_declaration: bool,
212) -> Result<String, EtreeError> {
213 let mut out = String::new();
214 if xml_declaration {
215 out.push_str("<?xml version='1.0' encoding='UTF-8'?>\n");
216 }
217 write_element(&mut out, root, 0, pretty_print)?;
218 if pretty_print {
219 out.push('\n');
220 }
221 Ok(out)
222}
223
224fn clark(namespace: Option<&str>, name: &str) -> String {
227 match namespace {
228 Some(ns) => format!("{{{ns}}}{name}"),
229 None => name.to_owned(),
230 }
231}
232
233fn convert(node: roxmltree::Node<'_, '_>) -> Result<Element, EtreeError> {
234 let tag = node.tag_name();
235 let mut element = Element::new(clark(tag.namespace(), tag.name()));
236 element.attrib = node
237 .attributes()
238 .map(|a| (clark(a.namespace(), a.name()), a.value().to_owned()))
239 .collect();
240 for child in node.children() {
241 if child.is_element() {
242 element.children.push(convert(child)?);
243 } else if child.is_text() {
244 let text = child.text().unwrap_or_default();
245 let slot = match element.children.last_mut() {
246 Some(last) => &mut last.tail,
247 None => &mut element.text,
248 };
249 slot.get_or_insert_with(String::new).push_str(text);
250 } else {
251 return Err(EtreeError(
252 "comments and processing instructions are not supported".into(),
253 ));
254 }
255 }
256 Ok(element)
257}
258
259pub fn fromstring(text: &str) -> Result<Element, EtreeError> {
263 let options = roxmltree::ParsingOptions {
264 allow_dtd: true,
265 ..Default::default()
266 };
267 let doc = roxmltree::Document::parse_with_options(text, options)
268 .map_err(|e| EtreeError(e.to_string()))?;
269 convert(doc.root_element())
270}
271
272#[cfg(test)]
273mod tests {
274 use super::*;
275
276 #[test]
277 fn lxml_pretty_print() -> Result<(), EtreeError> {
278 let mut root = Element::new("a");
279 let mut s = Element::new("string");
280 s.text = Some(String::new());
281 root.append(s);
282 let mut t = Element::new("t");
283 t.text = Some("x<>&\"\r\n\t".into());
284 t.set(format!("{XML_NS}lang"), "a\"<>&\n\r\t'");
285 root.append(t);
286 let mut e = Element::new("e");
287 e.append(Element::new("x"));
288 root.append(e);
289 assert_eq!(
291 tostring(&root, true, true)?,
292 "<?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"
293 );
294 Ok(())
295 }
296
297 #[test]
298 fn rejects_control_characters() {
299 let mut root = Element::new("a");
300 root.text = Some("\u{1}".into());
301 assert!(tostring(&root, true, true).is_err());
302 }
303}