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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
//! Structs for conversions from XML to JSON
//!
//! # Example
//! ```
//! use xmlJSON::XmlDocument;
//! use std::str::FromStr;
//! 
//! let test = "<note type=\"Reminder\">
//!                 test
//!             </note>";
//! let data = XmlDocument::from_str(test);


extern crate xml;
extern crate rustc_serialize;

use std::io::prelude::*;
use xml::reader::EventReader;
use xml::reader::events::*;
use std::str::FromStr;
use std::fmt;
use std::io::Cursor;
use rustc_serialize::json;
use std::collections::BTreeMap;

/// An XML Document
#[derive(Debug, Clone)]
pub struct XmlDocument {
    /// Data contained within the parsed XML Document
    pub data: Vec<XmlData>
}

// Print as JSON
impl fmt::Display for XmlDocument {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut s = String::new();

        for d in self.data.iter() {
            s = format!("{}{}", s, d);
        }

        s.fmt(f)
    }
}

/// An XML Tag
///
/// For exammple:
///
/// ```XML
/// <foo bar="baz">
///     test text
///     <sub></sub>
/// </foo>
/// ```
#[derive(Debug, Clone)]
pub struct XmlData {
    /// Name of the tag (i.e. "foo")
    pub name: String,
    /// Key-value pairs of the attributes (i.e. ("bar", "baz"))
    pub attributes: Vec<(String, String)>,
    /// Data (i.e. "test text")
    pub data: Option<String>,
    /// Sub elements (i.e. an XML element of "sub")
    pub sub_elements: Vec<XmlData>
}

// Generate indentation
fn indent(size: usize) -> String {
    const INDENT: &'static str = "    ";
    (0..size).map(|_| INDENT)
        .fold(String::with_capacity(size*INDENT.len()), |r, s| r + s)
}

// Get the attributes as a string 
fn attributes_to_string(attributes: &[(String, String)]) -> String {
    attributes.iter().fold(String::new(), |acc, &(ref k, ref v)|{
        format!("{} {}=\"{}\"", acc, k , v)
    })
}

// Format the XML data as a string
fn format(data: &XmlData, depth: usize) -> String {
    let sub =
        if data.sub_elements.is_empty() {
            String::new()
        } else {
            let mut sub = "\n".to_string();
            for elmt in data.sub_elements.iter() {
                sub = format!("{}{}", sub, format(elmt, depth + 1));
            }
            sub
        };

    let indt = indent(depth);

    let fmt_data = if let Some(ref d) = data.data {
        format!("\n{}{}", indent(depth+1), d)
    } else {
        "".to_string()
    };

    format!("{}<{}{}>{}{}\n{}</{}>", indt, data.name, attributes_to_string(&data.attributes), fmt_data, sub, indt, data.name)
}

impl fmt::Display for XmlData {
    fn fmt(&self, f : &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", format(self, 0)) 
    }
}

// Get the XML atributes as a string
fn map_owned_attributes(attrs: Vec<xml::attribute::OwnedAttribute>) -> Vec<(String, String)> {
    attrs.into_iter().map(|attr|{
        (attr.name.local_name, attr.value)
    }).collect()
}

// Parse the data
fn parse(mut data: Vec<XmlEvent>, current: Option<XmlData>, mut current_vec: Vec<XmlData>, trim: bool) -> (Vec<XmlData>, Vec<XmlEvent>) {
    if let Some(elmt) = data.pop() {
        match elmt {
            XmlEvent::StartElement{name, attributes, ..} => {
                let inner = XmlData{
                    name: name.local_name,
                    attributes: map_owned_attributes(attributes),
                    data: None,
                    sub_elements: Vec::new()
                };

                let (inner, rest) = parse(data, Some(inner), Vec::new(), trim);

                if let Some(mut crnt) = current {
                    crnt.sub_elements.extend(inner);
                    parse(rest, Some(crnt), current_vec, trim)
                } else {
                    current_vec.extend(inner);
                    parse(rest, None, current_vec, trim)
                }
            },
            XmlEvent::Characters(chr) => {
                let chr = if trim { chr.trim().to_string() } else {chr};
                if let Some(mut crnt) = current {
                    crnt.data = Some(chr);
                    parse(data, Some(crnt), current_vec, trim)

                } else {
                    panic!("Invalid form of XML doc");
                }
            },
            XmlEvent::EndElement{name} => {
                if let Some(crnt) = current {
                    if crnt.name == name.local_name {
                        current_vec.push(crnt);
                        return (current_vec, data)
                    } else {
                        panic!(format!("Invalid end tag: expected {}, got {}", crnt.name, name.local_name)) 
                    }
                } else {
                    panic!(format!("Invalid end tag: {}", name.local_name))
                }
            }
            _ => parse(data, current, current_vec, trim)
        }
    } else {
        if current.is_some() {
            panic!("Invalid end tag");
        } else {
            (current_vec, Vec::new())
        }
    }
}

impl XmlDocument {
    pub fn from_reader<R>(source : R, trim: bool) -> Self where R : Read {        
        let mut parser = EventReader::new(source);
        let mut events : Vec<XmlEvent> = parser.events().collect();
        events.reverse();
        let (data, _) = parse(events, None, Vec::new(), trim);
        XmlDocument{ data: data }
    }
}

/// Error when parsing XML
#[derive(Debug, Clone, PartialEq)]
pub struct ParseXmlError;

impl fmt::Display for ParseXmlError{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{
        "Could not parse string to XML".fmt(f)
    }
}

// Generate an XML document from a string
impl FromStr for XmlDocument {
    type Err = ParseXmlError;

    fn from_str(s: &str) -> Result<XmlDocument, ParseXmlError> {
        Ok(XmlDocument::from_reader(Cursor::new(s.to_string().into_bytes()), true))
    }

}

// Convert the data to an key-value pair of JSON
fn to_kv(data: &XmlData) -> (String, json::Json) {
    use rustc_serialize::json::ToJson;

    let mut map: BTreeMap<String, json::Json> = BTreeMap::new();
    if data.data.is_some(){
        map.insert("_".to_string(), data.data.clone().unwrap().to_json());
    }

    for (k, v) in data.sub_elements.iter().map(|x|{to_kv(x)}){
        map.insert(k, v);
    }

    let mut attr : BTreeMap<String, json::Json> = BTreeMap::new();
    for &(ref k, ref v) in data.attributes.iter() {
        attr.insert(k.clone(), v.to_json());
    }

    if !attr.is_empty() {
        map.insert("$".to_string(), attr.to_json());
    }

    (data.name.clone(), map.to_json())
}

impl json::ToJson for XmlDocument {
    fn to_json(&self) -> json::Json {
        let mut map: BTreeMap<String, json::Json> = BTreeMap::new();

        for (k, v) in self.data.iter().map(|x|{to_kv(x)}) {
            map.insert(k, v);
        }

        map.to_json() 
    }
}


#[cfg(test)]
mod tests {
    use super::XmlDocument;
    use std::io::Cursor;
    use std::str::FromStr;

    #[test]
    fn test_basic_xml(){
        let test = "<note type=\"Reminder\">
                        test
                    </note>".to_string();
        let data = XmlDocument::from_reader(Cursor::new(test.into_bytes()), true);
        assert_eq!(data.data.len(), 1);

        let ref data = data.data[0];
        assert_eq!(data.name, "note");

        let mut attrs = Vec::new();
        attrs.push(("type".to_string(), "Reminder".to_string()));

        assert_eq!(data.attributes, attrs);

        assert!(data.sub_elements.is_empty());

        assert_eq!(data.data, Some("test".to_string()));
    }

    #[test]
    fn test_from_str(){
        let test = "<note type=\"Reminder\">
                        test
                    </note>";
        let data = XmlDocument::from_str(test);
        assert!(data.is_ok());
        let data = data.unwrap();

        assert_eq!(data.data.len(), 1);

        let ref data = data.data[0];
        assert_eq!(data.name, "note");

        let mut attrs = Vec::new();
        attrs.push(("type".to_string(), "Reminder".to_string()));

        assert_eq!(data.attributes, attrs);

        assert!(data.sub_elements.is_empty());

        assert_eq!(data.data, Some("test".to_string()));
    }
}