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 package org.utgenome.gwt.utgb.client.util.xml;
26
27 import java.util.ArrayList;
28
29 public class XMLWriter {
30
31 private StringBuffer _out = new StringBuffer();
32 private ArrayList<String> _tagStack = new ArrayList<String>();
33 private int _currentLevel = 0;
34
35 public XMLWriter() {
36
37 }
38
39 @Override
40 public String toString() {
41 return _out.toString();
42 }
43
44 private void padding(int level) {
45 for (int i = 0; i < level; i++)
46 _out.append("\t");
47 }
48
49 public XMLWriter start(String tagName) {
50 return start(tagName, null);
51 }
52
53 public XMLWriter start(String tagName, String attribute, String attributeValue) {
54 return start(tagName, new XMLAttribute(attribute, attributeValue));
55 }
56
57 public XMLWriter start(String tagName, XMLAttribute attribute) {
58 padding(_currentLevel);
59 if (attribute == null)
60 _out.append("<" + tagName + ">");
61 else
62 _out.append("<" + tagName + " " + attribute.toString() + ">");
63 _out.append("\n");
64 pushTag(tagName);
65 return this;
66 }
67
68 private void pushTag(String tagName) {
69 _tagStack.add(tagName);
70 _currentLevel++;
71 }
72
73 private void popTag() {
74 _tagStack.remove(_tagStack.size() - 1);
75 _currentLevel--;
76 }
77
78 public XMLWriter text(String text) {
79 _out.append(text);
80 return this;
81 }
82
83 public XMLWriter element(String tagName, XMLAttribute attribute, String elementContent) {
84 padding(_currentLevel);
85 pushTag(tagName);
86 _out.append("<" + tagName + " " + attribute.toString() + ">");
87 _out.append(escape(elementContent));
88 _out.append("</" + tagName + ">\n");
89 popTag();
90 return this;
91 }
92
93 public XMLWriter element(String tagName, XMLAttribute attribute) {
94 padding(_currentLevel);
95 pushTag(tagName);
96 _out.append("<" + tagName + " " + attribute.toString() + "/>");
97 _out.append("\n");
98 popTag();
99 return this;
100 }
101
102 public static String escape(String text) {
103 if (text == null)
104 return text;
105
106 String value = text;
107 value = value.replaceAll("&", "&");
108 value = value.replaceAll("<", "<");
109 value = value.replaceAll(">", ">");
110 return value;
111 }
112
113 public XMLWriter end() {
114 if (_tagStack.size() == 0)
115 throw new IllegalStateException("no more tag to close");
116
117 padding(_currentLevel - 1);
118 String tagName = _tagStack.get(_tagStack.size() - 1);
119 _out.append("</" + tagName + ">");
120 _out.append("\n");
121
122 popTag();
123 return this;
124 }
125
126 public XMLWriter endDocument() {
127 for (int i = 0; i < _tagStack.size(); i++) {
128 end();
129 }
130 return this;
131 }
132
133 }