fontoxide_misc/
xml_reader.rs1use std::fmt;
13
14#[derive(Debug, Clone, PartialEq)]
16pub enum Content {
17 Text(String),
19 Element(Element),
21}
22
23impl Content {
24 pub fn as_element(&self) -> Option<&Element> {
26 match self {
27 Content::Element(e) => Some(e),
28 Content::Text(_) => None,
29 }
30 }
31
32 pub fn as_text(&self) -> Option<&str> {
34 match self {
35 Content::Text(t) => Some(t),
36 Content::Element(_) => None,
37 }
38 }
39}
40
41#[derive(Debug, Clone, PartialEq, Default)]
43pub struct Element {
44 pub name: String,
46 pub attrs: Vec<(String, String)>,
48 pub content: Vec<Content>,
50}
51
52impl Element {
53 pub fn attr(&self, name: &str) -> Option<&str> {
55 self.attrs
56 .iter()
57 .find(|(n, _)| n == name)
58 .map(|(_, v)| v.as_str())
59 }
60
61 pub fn elements(&self) -> impl Iterator<Item = &Element> {
64 self.content.iter().filter_map(Content::as_element)
65 }
66
67 pub fn text(&self) -> String {
69 self.content.iter().filter_map(Content::as_text).collect()
70 }
71
72 pub fn text_chunks(&self) -> impl Iterator<Item = &str> {
74 self.content.iter().filter_map(Content::as_text)
75 }
76}
77
78#[derive(Debug, Clone, PartialEq, Eq)]
80pub struct ParseError(pub String);
81
82impl fmt::Display for ParseError {
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 f.write_str(&self.0)
85 }
86}
87
88impl std::error::Error for ParseError {}
89
90pub fn parse(text: &str) -> Result<Element, ParseError> {
92 let options = roxmltree::ParsingOptions {
93 allow_dtd: true,
94 ..Default::default()
95 };
96 let doc = roxmltree::Document::parse_with_options(text, options)
97 .map_err(|e| ParseError(e.to_string()))?;
98 Ok(convert(doc.root_element()))
99}
100
101fn convert(node: roxmltree::Node<'_, '_>) -> Element {
102 let mut element = Element {
103 name: node.tag_name().name().to_owned(),
104 attrs: node
105 .attributes()
106 .map(|a| (attr_name(&a), a.value().to_owned()))
107 .collect(),
108 content: Vec::new(),
109 };
110 for child in node.children() {
111 if child.is_element() {
112 element.content.push(Content::Element(convert(child)));
113 } else if child.is_text() {
114 push_text(&mut element.content, child.text().unwrap_or_default());
115 }
116 }
117 element
118}
119
120fn attr_name(a: &roxmltree::Attribute<'_, '_>) -> String {
121 match a.namespace() {
124 Some("http://www.w3.org/XML/1998/namespace") => format!("xml:{}", a.name()),
125 _ => a.name().to_owned(),
126 }
127}
128
129fn push_text(content: &mut Vec<Content>, text: &str) {
131 for (i, piece) in text.split('\n').enumerate() {
132 if i > 0 {
133 append_chunk(content, "\n");
134 }
135 if !piece.is_empty() {
136 append_chunk(content, piece);
137 }
138 }
139}
140
141fn append_chunk(content: &mut Vec<Content>, data: &str) {
142 if data != "\n"
143 && let Some(Content::Text(last)) = content.last_mut()
144 && last != "\n"
145 {
146 last.push_str(data);
147 return;
148 }
149 content.push(Content::Text(data.to_owned()));
150}
151
152#[cfg(test)]
153mod tests {
154 use super::*;
155
156 #[test]
157 fn content_model() {
158 let root = parse("<a x=\"1\">\n <b/>\n text & more\n</a>").expect("valid xml");
159 assert_eq!(root.name, "a");
160 assert_eq!(root.attr("x"), Some("1"));
161 let texts: Vec<_> = root.text_chunks().collect();
162 assert_eq!(texts, ["\n", " ", "\n", " text & more", "\n"]);
163 assert_eq!(root.elements().count(), 1);
164 }
165
166 #[test]
167 fn crlf_is_normalized() {
168 let root = parse("<a>x\r\ny</a>").expect("valid xml");
169 let texts: Vec<_> = root.text_chunks().collect();
170 assert_eq!(texts, ["x", "\n", "y"]);
171 }
172}