edit_xml/element/
debug.rs

1use std::fmt::Debug;
2
3use crate::Document;
4
5use super::Element;
6
7/// Debug implementation for Element
8///
9/// This is a wrapper around Element that implements Debug that will debugs the full element
10///
11/// This will hold a reference to the Document to get the name of the element and its attributes
12pub struct ElementDebug<'element, 'doc> {
13    pub(crate) element: &'element Element,
14    pub(crate) doc: &'doc Document,
15    // TODO: Possible depth limit?
16}
17impl<'element, 'doc> ElementDebug<'element, 'doc> {
18    /// Create a new ElementDebug
19    pub fn new(element: &'element Element, doc: &'doc Document) -> Self {
20        Self { element, doc }
21    }
22}
23impl Debug for ElementDebug<'_, '_> {
24    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25        let Self { element, doc } = self;
26        let name = element.name(doc);
27        let attributes = element.attributes(doc);
28        let children = element.children(doc);
29        if children.is_empty() {
30            return f
31                .debug_struct("Element")
32                .field("name", &name)
33                .field("attributes", &attributes)
34                .finish();
35        }
36
37        if children.len() == 1 && children[0].is_text() {
38            // If it only has one child and that child is a text node, then we can just print the text
39            let text = children[0].text_content(doc);
40            return f
41                .debug_struct("Element")
42                .field("name", &name)
43                .field("attributes", &attributes)
44                .field("text", &text)
45                .finish();
46        }
47        // Full debug of the children
48        let children: Vec<_> = element
49            .children(doc)
50            .iter()
51            .map(|child| child.debug(doc))
52            .collect();
53        f.debug_struct("Element")
54            .field("name", &name)
55            .field("attributes", &attributes)
56            .field("children", &children)
57            .finish()
58    }
59}