Skip to main content

parsec_xml/
serialize.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! Writing a document back out as XML, with every prefix and namespace
5//! declaration as it was, so it parses back to the same tree.
6
7use std::collections::HashSet;
8
9use crate::tree::{Data, Document, NONE, NodeId, XMLNS_NS};
10
11fn escape_text(s: &str, out: &mut String) {
12    let mut from = 0;
13    for (i, b) in s.bytes().enumerate() {
14        let r = match b {
15            b'&' => "&",
16            b'<' => "&lt;",
17            b'>' => "&gt;",
18            // A CR would read back as a line end.
19            b'\r' => "&#13;",
20            _ => continue,
21        };
22        out.push_str(&s[from..i]);
23        out.push_str(r);
24        from = i + 1;
25    }
26    out.push_str(&s[from..]);
27}
28
29fn escape_attr(s: &str, out: &mut String) {
30    let mut from = 0;
31    for (i, b) in s.bytes().enumerate() {
32        let r = match b {
33            b'&' => "&amp;",
34            b'<' => "&lt;",
35            b'"' => "&quot;",
36            // White space that normalization would turn into spaces.
37            b'\t' => "&#9;",
38            b'\n' => "&#10;",
39            b'\r' => "&#13;",
40            _ => continue,
41        };
42        out.push_str(&s[from..i]);
43        out.push_str(r);
44        from = i + 1;
45    }
46    out.push_str(&s[from..]);
47}
48
49fn quote(s: &str, out: &mut String) {
50    let q = if s.contains('"') { '\'' } else { '"' };
51    out.push(q);
52    out.push_str(s);
53    out.push(q);
54}
55
56impl Document {
57    /// The whole document as XML: the XML declaration (without an
58    /// encoding, since this is a string), the `<!DOCTYPE>` with its
59    /// internal subset as written, and the tree. Entity references come
60    /// out expanded, but for those to entities Parsec didn't read.
61    /// Attributes the DTD defaulted are left to the DTD.
62    ///
63    /// ```
64    /// let src = r#"<feed xmlns="http://www.w3.org/2005/Atom" xmlns:m="urn:m"><m:x a="1 &amp; 2"/></feed>"#;
65    /// let doc = parsec_xml::parse(src).unwrap();
66    /// assert_eq!(doc.to_xml(), src);
67    /// ```
68    pub fn to_xml(&self) -> String {
69        let mut out = String::new();
70        if let Some(decl) = &self.decl {
71            out.push_str("<?xml version=\"");
72            out.push_str(&decl.version);
73            out.push('"');
74            if let Some(sd) = decl.standalone {
75                out.push_str(if sd {
76                    " standalone=\"yes\""
77                } else {
78                    " standalone=\"no\""
79                });
80            }
81            out.push_str("?>");
82        }
83        for (i, child) in self.children(self.root()).enumerate() {
84            if i > 0 || self.decl.is_some() {
85                out.push('\n');
86            }
87            self.write(child, false, &mut out);
88        }
89        out
90    }
91
92    /// A node and everything under it as XML. An element written alone
93    /// takes along the namespace declarations it's in the scope of, and
94    /// the attributes the DTD defaulted on it and under it, so that it
95    /// means the same on its own.
96    pub fn write_xml(&self, node: NodeId, out: &mut String) {
97        if node == self.root() {
98            out.push_str(&self.to_xml());
99        } else {
100            self.write(node, true, out);
101        }
102    }
103
104    fn write(&self, top: NodeId, alone: bool, out: &mut String) {
105        let mut n = top.0;
106        loop {
107            let node = &self.nodes[n as usize];
108            self.open(NodeId(n), alone && n == top.0, alone, out);
109            if node.first != NONE {
110                n = node.first;
111                continue;
112            }
113            loop {
114                if n == top.0 {
115                    return;
116                }
117                let node = &self.nodes[n as usize];
118                if node.next != NONE {
119                    n = node.next;
120                    break;
121                }
122                n = node.parent;
123                self.close(NodeId(n), out);
124            }
125        }
126    }
127
128    fn open(&self, n: NodeId, top: bool, defaults: bool, out: &mut String) {
129        match self.nodes[n.index()].data {
130            Data::Element { .. } => {
131                let name = self.name(n).unwrap();
132                out.push('<');
133                out.push_str(name.qname);
134                for a in self.attributes(n) {
135                    if a.specified || defaults {
136                        out.push(' ');
137                        out.push_str(a.name.qname);
138                        out.push_str("=\"");
139                        escape_attr(a.value, out);
140                        out.push('"');
141                    }
142                }
143                if top {
144                    self.inherited_declarations(n, out);
145                }
146                out.push_str(if self.nodes[n.index()].first == NONE {
147                    "/>"
148                } else {
149                    ">"
150                });
151            }
152            Data::Text(s) => escape_text(self.str(s), out),
153            Data::Cdata(s) => {
154                out.push_str("<![CDATA[");
155                out.push_str(self.str(s));
156                out.push_str("]]>");
157            }
158            Data::Comment(s) => {
159                out.push_str("<!--");
160                out.push_str(self.str(s));
161                out.push_str("-->");
162            }
163            Data::Pi { target, data } => {
164                out.push_str("<?");
165                out.push_str(self.str(target));
166                if data.len > 0 {
167                    out.push(' ');
168                    out.push_str(self.str(data));
169                }
170                out.push_str("?>");
171            }
172            Data::EntityRef(s) => {
173                out.push('&');
174                out.push_str(self.str(s));
175                out.push(';');
176            }
177            Data::Doctype => {
178                let Some(d) = &self.doctype else { return };
179                out.push_str("<!DOCTYPE ");
180                out.push_str(&d.name);
181                match (&d.public_id, &d.system_id) {
182                    (Some(p), Some(s)) => {
183                        out.push_str(" PUBLIC ");
184                        quote(p, out);
185                        out.push(' ');
186                        quote(s, out);
187                    }
188                    (None, Some(s)) => {
189                        out.push_str(" SYSTEM ");
190                        quote(s, out);
191                    }
192                    _ => {}
193                }
194                if let Some(subset) = &d.internal_subset {
195                    out.push_str(" [");
196                    out.push_str(subset);
197                    out.push(']');
198                }
199                out.push('>');
200            }
201            Data::Document => {}
202        }
203    }
204
205    fn close(&self, n: NodeId, out: &mut String) {
206        if let Some(name) = self.name(n) {
207            out.push_str("</");
208            out.push_str(name.qname);
209            out.push('>');
210        }
211    }
212
213    /// The declarations in scope at `n` from its ancestors that it
214    /// doesn't make itself, nearest first.
215    fn inherited_declarations(&self, n: NodeId, out: &mut String) {
216        let mut seen: HashSet<&str> = self
217            .attributes(n)
218            .filter(|a| a.is_namespace_declaration())
219            .map(|a| a.name.qname)
220            .collect();
221        for up in self.ancestors(n) {
222            for a in self.attributes(up) {
223                if a.name.namespace != XMLNS_NS || !seen.insert(a.name.qname) {
224                    continue;
225                }
226                // No default namespace above is the same as none at all.
227                if a.name.qname == "xmlns" && a.value.is_empty() {
228                    continue;
229                }
230                out.push(' ');
231                out.push_str(a.name.qname);
232                out.push_str("=\"");
233                escape_attr(a.value, out);
234                out.push('"');
235            }
236        }
237    }
238}