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
use super::namespaces::Namespace;

#[derive(Debug, PartialEq)]
pub struct Attribute<'a> {
    namespace: &'a Namespace,
    name: String,
    value: String,
}
impl<'a> Attribute<'a> {
    pub fn new(namespace: &'a Namespace, name: String, value: String) -> Attribute<'a> {
        Attribute {
            namespace,
            name,
            value,
        }
    }
}

#[derive(Debug, PartialEq)]
pub struct Comment {
    data: String,
}

#[derive(Debug, PartialEq)]
pub struct DocumentFragment<'a> {
    children: Vec<Node<'a>>,
}

#[derive(Debug, PartialEq)]
pub struct Element<'a> {
    namespace: &'a Namespace,
    local_name: String,
    attributes: Vec<Attribute<'a>>,
    children: Vec<Node<'a>>,
}

#[derive(Debug, PartialEq)]
pub struct Text {
    data: String,
}

#[derive(Debug, PartialEq)]
pub enum Node<'a> {
    CommentNode(Comment),
    DocumentFragmentNode(DocumentFragment<'a>),
    ElementNode(Element<'a>),
    TextNode(Text),
}

impl<'a> Node<'a> {
    pub fn new_comment(data: String) -> Node<'a> {
        Node::CommentNode(Comment { data })
    }

    pub fn new_document_fragment(children: Vec<Node<'a>>) -> Node<'a> {
        Node::DocumentFragmentNode(DocumentFragment { children })
    }

    pub fn new_element(
        namespace: &'a Namespace,
        local_name: String,
        attributes: Vec<Attribute<'a>>,
        children: Vec<Node<'a>>,
    ) -> Node<'a> {
        Node::ElementNode(Element {
            namespace,
            local_name,
            attributes,
            children,
        })
    }

    pub fn new_text(data: String) -> Node<'a> {
        Node::TextNode(Text { data })
    }
}

pub struct Serializer {}

impl Serializer {
    pub fn new() -> Serializer {
        Serializer {}
    }

    pub fn serialize(&self, namespace: &Namespace, node: Node) -> String {
        let mut xml = String::new();

        match node {
            Node::CommentNode(c) => {
                xml.push_str(&format!("<!--{}-->", &c.data));
            }
            Node::DocumentFragmentNode(document_fragment) => {
                if document_fragment.children.len() > 0 {
                    for child in document_fragment.children {
                        xml.push_str(&self.serialize(namespace, child));
                    }
                }
            }
            Node::ElementNode(e) => {
                if e.namespace == namespace {
                    xml.push_str(&format!("<{}", &e.local_name));
                } else {
                    xml.push_str(&format!(
                        "<{} xmlns=\"{}\"",
                        &e.local_name, &e.namespace.uri
                    ));
                }

                if e.attributes.len() > 0 {
                    for attr in e.attributes {
                        if attr.namespace == e.namespace {
                            xml.push_str(&format!(" {}=\"{}\"", &attr.name, &attr.value));
                        } else {
                            xml.push_str(&format!(
                                " {}:{}=\"{}\"",
                                &attr.namespace.prefix, &attr.name, &attr.value
                            ));
                        }
                    }
                }

                if e.children.len() == 0 {
                    xml.push_str("/>");
                } else {
                    xml.push_str(">");

                    for child in e.children {
                        xml.push_str(&self.serialize(e.namespace, child));
                    }

                    xml.push_str(&format!("</{}>", &e.local_name));
                }
            }
            Node::TextNode(t) => {
                xml.push_str(&t.data);
            }
        }

        xml
    }
}

#[cfg(test)]
mod tests {
    use super::super::namespaces::NamespaceRegistry;
    use super::*;

    #[test]
    fn new_namespaces() {
        let nr = NamespaceRegistry::new();
        let xmlns = nr.get("xml").unwrap();
        assert_eq!(xmlns.prefix, "xml");
        assert_eq!(xmlns.uri, "http://www.w3.org/XML/1998/namespace");

        let xhtmlns = nr.get("xhtml").unwrap();
        assert_eq!(xhtmlns.prefix, "xhtml");
        assert_eq!(xhtmlns.uri, "http://www.w3.org/1999/xhtml");

        let mathmlns = nr.get("mathml").unwrap();
        assert_eq!(mathmlns.prefix, "mathml");
        assert_eq!(mathmlns.uri, "http://www.w3.org/1998/Math/MathML");

        let svgns = nr.get("svg").unwrap();
        assert_eq!(svgns.prefix, "svg");
        assert_eq!(svgns.uri, "http://www.w3.org/2000/svg");
    }

    #[test]
    fn serializing() {
        let nr = NamespaceRegistry::new();
        let xmlns = nr.get("xml").unwrap();
        let xhtmlns = nr.get("xhtml").unwrap();

        let text = Node::new_text("Example text.".to_owned());
        let comment = Node::new_comment("Example comment.".to_owned());
        let attribute = Attribute::new(&xhtmlns, "title".to_owned(), "My tooltip.".to_owned());
        let br = Node::new_element(&xhtmlns, "br".to_owned(), vec![], vec![]);
        let p = Node::new_element(
            &xhtmlns,
            "p".to_owned(),
            vec![attribute],
            vec![text, br, comment],
        );

        let serializer = Serializer::new();
        let xml = serializer.serialize(&xmlns, p);

        assert_eq!(
            xml,
            "<p xmlns=\"http://www.w3.org/1999/xhtml\" title=\"My tooltip.\">Example text.<br/><!--Example comment.--></p>"
        );
        println!("xml={}", xml);
    }
}