summaryrefslogtreecommitdiffstats
blob: 6a51d3f225c6c020ae22e62d3c2998bb01761e34 (plain)
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
/*
 * Copyright (c) 2010-2012, Isode Limited, London, England.
 * All rights reserved.
 */
/*
 * Copyright (c) 2010, Remko Tronçon.
 * All rights reserved.
 */
package com.isode.stroke.serializer.xml;

import java.util.Map;
import java.util.TreeMap;
import java.util.Vector;

public class XMLElement implements XMLNode {

    private final String tag_;
    private final Map<String, String> attributes_ = new TreeMap<String, String>();
    private final Vector<XMLNode> childNodes_ = new Vector<XMLNode>();

    public XMLElement(String tag) {
        this(tag, "");
    }

    public XMLElement(String tag, String xmlns) {
        tag_ = tag;
        if (xmlns.length()!=0) {
            setAttribute("xmlns", xmlns);
        }
    }

    public XMLElement(String tag, String xmlns, String text) {
        this(tag, xmlns);
        if (text.length() > 0) {
            addNode(new XMLTextNode(text));
        }
    }

    public String serialize() {
        StringBuilder result = new StringBuilder();
        result.append("<").append(tag_);
        for (String key : attributes_.keySet()) {
            result.append(" ").append(key).append("=\"").append(attributes_.get(key)).append("\"");
        }

        if (childNodes_.size() > 0) {
            result.append(">");
            for (XMLNode node : childNodes_) {
                result.append(node.serialize());
            }
            result.append("</").append(tag_).append(">");
        } else {
            result.append("/>");
        }
        return result.toString();
    }

    public void setAttribute(String attribute, String value) {
        String escapedValue = value;
        escapedValue = escapedValue.replaceAll("&", "&amp;");
        escapedValue = escapedValue.replaceAll("<", "&lt;");
        escapedValue = escapedValue.replaceAll(">", "&gt;");
        escapedValue = escapedValue.replaceAll("'", "&apos;");
        escapedValue = escapedValue.replaceAll("\"", "&quot;");
        attributes_.put(attribute, escapedValue);
    }

    public void addNode(XMLNode node) {
        childNodes_.add(node);
    }
}