1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
//! `simple_xml_builder` provides basic functionality for building and outputing
//! xml documents.
//!
//! The constructed model is write-only.
//!
//! # Usage
//!
//! Use [XMLElement](struct.XMLElement.html) to create elements with tags,
//! attributes, and either text or children.
//! You can write an XML document by calling
//! [write](struct.XMLElement.html#method.write) on your root element.
//!
//! # Example
//!
//! ```rust
//! # use std::io;
//! # fn main() -> io::Result<()> {
//! use std::fs::File;
//! use simple_xml_builder::XMLElement;
//!
//! let mut file = File::create("sample.xml")?;
//!
//! let mut person = XMLElement::new("person");
//! person.add_attribute("id", "232");
//! let mut name = XMLElement::new("name");
//! name.add_text("Joe Schmoe");
//! person.add_child(name);
//! let mut age = XMLElement::new("age");
//! age.add_text("24");
//! person.add_child(age);
//! let hobbies = XMLElement::new("hobbies");
//! person.add_child(hobbies);
//!
//! person.write(file)?;
//! # Ok(())
//! # }
//! ```
//! `sample.xml` will contain:
//! ```xml
//! <?xml version = "1.0" encoding = "UTF-8"?>
//! <person id="232">
//!     <name>Joe Schmoe</name>
//!     <age>24</age>
//!     <hobbies />
//! </person>
//! ```

#![doc(html_root_url = "https://docs.rs/simple-xml-builder/1.0.0")]

extern crate indexmap;
use indexmap::IndexMap;
use std::fmt;
use std::io::{self, Write};

/// Represents an XML element
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct XMLElement {
    name: String,
    attributes: IndexMap<String, String>,
    content: XMLElementContent,
}

#[derive(Debug, Clone, Eq, PartialEq)]
enum XMLElementContent {
    Empty,
    Elements(Vec<XMLElement>),
    Text(String),
}

impl fmt::Display for XMLElement {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut s: Vec<u8> = Vec::new();
        self.write(&mut s)
            .expect("Failure writing output to Vec<u8>");
        write!(f, "{}", unsafe { String::from_utf8_unchecked(s) })
    }
}

impl XMLElement {
    /// Creates a new empty XML element using the given name for the tag.
    pub fn new(name: &str) -> Self {
        XMLElement {
            name: name.to_owned(),
            attributes: IndexMap::new(),
            content: XMLElementContent::Empty,
        }
    }

    /// Adds an attribute to the XML element.
    pub fn add_attribute(&mut self, name: &str, value: &str) {
        self.attributes.insert(name.to_owned(), escape_str(value));
    }

    /// Adds a child element to the XML element.
    /// The new child will be placed after previously added children.
    ///
    /// This method may only be called on an element that has children or is
    /// empty.
    ///
    /// # Panics
    ///
    /// Panics if the element contains text.
    pub fn add_child(&mut self, child: XMLElement) {
        use XMLElementContent::*;
        match self.content {
            Empty => {
                self.content = Elements(vec![child]);
            }
            Elements(ref mut list) => {
                list.push(child);
            }
            Text(_) => {
                panic!("Attempted adding child element to element with text.");
            }
        }
    }

    /// Adds text to the XML element.
    ///
    /// This method may only be called on an empty element.
    ///
    /// # Panics
    ///
    /// Panics if the element is not empty.
    pub fn add_text(&mut self, text: &str) {
        use XMLElementContent::*;
        match self.content {
            Empty => {
                self.content = Text(escape_str(text));
            }
            _ => {
                panic!("Attempted adding text to non-empty element.");
            }
        }
    }

    /// Outputs an utf8 XML document, where this element is the root element.
    ///
    /// Output is properly indented.
    ///
    /// # Errors
    ///
    /// Returns Errors from writing to the Write object.
    pub fn write<W: Write>(&self, mut writer: W) -> io::Result<()> {
        writeln!(writer, r#"<?xml version = "1.0" encoding = "UTF-8"?>"#)?;
        self.write_level(&mut writer, 0)
    }

    fn write_level<W: Write>(&self, writer: &mut W, level: usize) -> io::Result<()> {
        use XMLElementContent::*;
        let prefix = "\t".repeat(level);
        match &self.content {
            Empty => {
                writeln!(
                    writer,
                    "{}<{}{} />",
                    prefix,
                    self.name,
                    self.attribute_string()
                )?;
            }
            Elements(list) => {
                writeln!(
                    writer,
                    "{}<{}{}>",
                    prefix,
                    self.name,
                    self.attribute_string()
                )?;
                for elem in list {
                    elem.write_level(writer, level + 1)?;
                }
                writeln!(writer, "{}</{}>", prefix, self.name)?;
            }
            Text(text) => {
                writeln!(
                    writer,
                    "{}<{}{}>{}</{1}>",
                    prefix,
                    self.name,
                    self.attribute_string(),
                    text
                )?;
            }
        }
        Ok(())
    }

    fn attribute_string(&self) -> String {
        if self.attributes.is_empty() {
            "".to_owned()
        } else {
            let mut result = "".to_owned();
            for (k, v) in &self.attributes {
                result = result + &format!(r#" {}="{}""#, k, v);
            }
            result
        }
    }
}

fn escape_str(input: &str) -> String {
    input
        .to_owned()
        .replace('&', "&amp;")
        .replace('"', "&quot;")
        .replace('\'', "&apos;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
}

#[cfg(test)]
mod tests {
    use XMLElement;

    #[test]
    fn write_xml() {
        let mut root = XMLElement::new("root");
        let mut child1 = XMLElement::new("child1");
        let inner1 = XMLElement::new("inner");
        child1.add_child(inner1);
        let mut inner2 = XMLElement::new("inner");
        inner2.add_text("Example Text\nNew line");
        child1.add_child(inner2);
        root.add_child(child1);
        let mut child2 = XMLElement::new("child2");
        child2.add_attribute("at1", "test &");
        child2.add_attribute("at2", "test <");
        child2.add_attribute("at3", "test \"");
        let mut inner3 = XMLElement::new("inner");
        inner3.add_attribute("test", "example");
        child2.add_child(inner3);
        root.add_child(child2);
        let mut child3 = XMLElement::new("child3");
        child3.add_text("&< &");
        root.add_child(child3);

        let expected = r#"<?xml version = "1.0" encoding = "UTF-8"?>
<root>
	<child1>
		<inner />
		<inner>Example Text
New line</inner>
	</child1>
	<child2 at1="test &amp;" at2="test &lt;" at3="test &quot;">
		<inner test="example" />
	</child2>
	<child3>&amp;&lt; &amp;</child3>
</root>
"#;
        assert_eq!(
            format!("{}", root),
            expected,
            "Attempt to write XML did not give expected results."
        );
    }

    #[test]
    #[should_panic]
    fn add_text_to_parent_element() {
        let mut e = XMLElement::new("test");
        e.add_child(XMLElement::new("test"));
        e.add_text("example text");
    }

    #[test]
    #[should_panic]
    fn add_child_to_text_element() {
        let mut e = XMLElement::new("test");
        e.add_text("example text");
        e.add_child(XMLElement::new("test"));
    }
}