Skip to main content

deepdoc_core/extract/
xml.rs

1//! A tiny XML tree, shared by the OOXML and ODF extractors.
2//!
3//! The office formats need to look *around* an element (a paragraph's style
4//! lives in a sibling subtree, a hyperlink target in another file), which a
5//! streaming reader makes awkward. Parsing into a small tree first keeps each
6//! extractor readable; the documents involved are already fully in memory
7//! because they come out of a ZIP entry.
8//!
9//! Names are stored without their prefix: OOXML and ODF use fixed, well-known
10//! prefixes (`w:`, `a:`, `text:`, `table:`), and matching on local names keeps
11//! the extractors free of namespace plumbing.
12
13use quick_xml::events::Event;
14use quick_xml::{Reader, XmlVersion};
15
16/// An XML element: local name, attributes and children.
17#[derive(Debug, Clone, PartialEq, Default)]
18pub struct Element {
19    pub name: String,
20    pub attrs: Vec<(String, String)>,
21    pub children: Vec<Node>,
22}
23
24/// A child of an element.
25#[derive(Debug, Clone, PartialEq)]
26pub enum Node {
27    Element(Element),
28    Text(String),
29}
30
31impl Element {
32    /// Value of an attribute, matched on its local name.
33    pub fn attr(&self, name: &str) -> Option<&str> {
34        self.attrs
35            .iter()
36            .find(|(key, _)| key == name)
37            .map(|(_, value)| value.as_str())
38    }
39
40    /// An attribute parsed as a number.
41    pub fn attr_number(&self, name: &str) -> Option<i64> {
42        self.attr(name)?.trim().parse().ok()
43    }
44
45    /// Direct child elements, in document order.
46    pub fn elements(&self) -> impl Iterator<Item = &Element> {
47        self.children.iter().filter_map(|node| match node {
48            Node::Element(element) => Some(element),
49            Node::Text(_) => None,
50        })
51    }
52
53    /// First direct child with this name.
54    pub fn child(&self, name: &str) -> Option<&Element> {
55        self.elements().find(|element| element.name == name)
56    }
57
58    /// Follow a chain of direct children: `element.path(["pPr", "pStyle"])`.
59    pub fn path<'a, I>(&self, names: I) -> Option<&Element>
60    where
61        I: IntoIterator<Item = &'a str>,
62    {
63        let mut current = self;
64        for name in names {
65            current = current.child(name)?;
66        }
67        Some(current)
68    }
69
70    /// First descendant with this name, depth first.
71    pub fn find(&self, name: &str) -> Option<&Element> {
72        if self.name == name {
73            return Some(self);
74        }
75        self.elements().find_map(|child| child.find(name))
76    }
77
78    /// Every descendant with this name. Does not descend into a match, so
79    /// nested structures (a list inside a list item) stay for the caller.
80    pub fn find_all(&self, name: &str) -> Vec<&Element> {
81        let mut found = Vec::new();
82        self.collect(name, &mut found);
83        found
84    }
85
86    fn collect<'a>(&'a self, name: &str, found: &mut Vec<&'a Element>) {
87        for child in self.elements() {
88            if child.name == name {
89                found.push(child);
90            } else {
91                child.collect(name, found);
92            }
93        }
94    }
95
96    /// All text under this element, concatenated.
97    pub fn text(&self) -> String {
98        let mut out = String::new();
99        self.write_text(&mut out);
100        out
101    }
102
103    fn write_text(&self, out: &mut String) {
104        for child in &self.children {
105            match child {
106                Node::Text(text) => out.push_str(text),
107                Node::Element(element) => element.write_text(out),
108            }
109        }
110    }
111}
112
113/// Parse a document and return its root element.
114pub fn parse(xml: &str) -> std::result::Result<Element, String> {
115    let mut reader = Reader::from_str(xml);
116    reader.config_mut().expand_empty_elements = false;
117
118    let mut stack: Vec<Element> = vec![Element::default()];
119
120    loop {
121        match reader.read_event() {
122            Ok(Event::Start(start)) => stack.push(element_from(&start)),
123            Ok(Event::Empty(empty)) => {
124                let element = element_from(&empty);
125                push_child(&mut stack, Node::Element(element));
126            }
127            Ok(Event::End(_)) => {
128                if stack.len() > 1 {
129                    let element = stack.pop().expect("checked length");
130                    push_child(&mut stack, Node::Element(element));
131                }
132            }
133            Ok(Event::Text(text)) => {
134                if let Ok(text) = text.xml10_content()
135                    && !text.is_empty()
136                {
137                    push_child(&mut stack, Node::Text(text.to_string()));
138                }
139            }
140            Ok(Event::CData(data)) => {
141                if let Ok(text) = data.decode() {
142                    push_child(&mut stack, Node::Text(text.to_string()));
143                }
144            }
145            // In quick-xml 0.41 entity references arrive as their own events.
146            Ok(Event::GeneralRef(reference)) => {
147                if let Some(text) = resolve_entity(&reference) {
148                    push_child(&mut stack, Node::Text(text));
149                }
150            }
151            Ok(Event::Eof) => break,
152            Ok(_) => {}
153            Err(error) => return Err(error.to_string()),
154        }
155    }
156
157    // Unwrap the virtual root and hand back the document element.
158    let root = stack.swap_remove(0);
159    root.elements()
160        .next()
161        .cloned()
162        .ok_or_else(|| "the document has no root element".to_string())
163}
164
165fn element_from(start: &quick_xml::events::BytesStart<'_>) -> Element {
166    let name = String::from_utf8_lossy(start.local_name().as_ref()).to_string();
167
168    let attrs = start
169        .attributes()
170        .filter_map(Result::ok)
171        .filter_map(|attr| {
172            let key = String::from_utf8_lossy(attr.key.local_name().as_ref()).to_string();
173            let value = attr
174                .decoded_and_normalized_value(XmlVersion::Explicit1_0, reader_decoder())
175                .ok()?;
176            Some((key, value.to_string()))
177        })
178        .collect();
179
180    Element {
181        name,
182        attrs,
183        children: Vec::new(),
184    }
185}
186
187/// OOXML and ODF are always UTF-8, so the default decoder is the right one.
188fn reader_decoder() -> quick_xml::Decoder {
189    quick_xml::Reader::from_str("").decoder()
190}
191
192fn push_child(stack: &mut [Element], node: Node) {
193    if let Some(parent) = stack.last_mut() {
194        // Merge adjacent text so entity references do not split a run.
195        if let (Node::Text(text), Some(Node::Text(previous))) = (&node, parent.children.last_mut())
196        {
197            previous.push_str(text);
198            return;
199        }
200        parent.children.push(node);
201    }
202}
203
204fn resolve_entity(reference: &quick_xml::events::BytesRef<'_>) -> Option<String> {
205    if let Ok(Some(ch)) = reference.resolve_char_ref() {
206        return Some(ch.to_string());
207    }
208    let name = reference.decode().ok()?;
209    let resolved = match name.as_ref() {
210        "lt" => "<",
211        "gt" => ">",
212        "amp" => "&",
213        "quot" => "\"",
214        "apos" => "'",
215        _ => return None,
216    };
217    Some(resolved.to_string())
218}
219
220#[cfg(test)]
221mod tests {
222    use super::*;
223
224    #[test]
225    fn parses_elements_attributes_and_text() {
226        let root = parse(r#"<w:p w:rsid="1"><w:r><w:t>hello</w:t></w:r></w:p>"#).unwrap();
227        assert_eq!(root.name, "p");
228        assert_eq!(root.attr("rsid"), Some("1"));
229        assert_eq!(root.text(), "hello");
230    }
231
232    #[test]
233    fn keeps_empty_elements_as_children() {
234        let root = parse("<p><br/><t>after</t></p>").unwrap();
235        let names: Vec<&str> = root.elements().map(|e| e.name.as_str()).collect();
236        assert_eq!(names, vec!["br", "t"]);
237    }
238
239    #[test]
240    fn resolves_entities_into_one_text_run() {
241        let root = parse("<t>a &amp; b &#65;</t>").unwrap();
242        assert_eq!(root.text(), "a & b A");
243        assert_eq!(root.children.len(), 1, "text should be merged: {root:?}");
244    }
245
246    #[test]
247    fn find_all_does_not_descend_into_matches() {
248        let root =
249            parse("<body><list><item><list><item>deep</item></list></item></list></body>").unwrap();
250        let lists = root.find_all("list");
251        assert_eq!(lists.len(), 1);
252        assert_eq!(lists[0].find_all("item").len(), 1);
253    }
254
255    #[test]
256    fn path_walks_direct_children_only() {
257        let root = parse("<p><pPr><pStyle val=\"Heading1\"/></pPr><r><t>x</t></r></p>").unwrap();
258        assert_eq!(
259            root.path(["pPr", "pStyle"]).and_then(|e| e.attr("val")),
260            Some("Heading1")
261        );
262        assert!(root.path(["pStyle"]).is_none());
263    }
264
265    #[test]
266    fn malformed_xml_is_an_error() {
267        assert!(parse("<a><b></a>").is_err());
268        assert!(parse("").is_err());
269    }
270}