1466
|
1 package goodjava.xml;
|
|
2
|
|
3 import java.util.Map;
|
|
4
|
|
5
|
|
6 public final class XmlElement {
|
|
7 public final String name;
|
|
8 public final Map<String,String> attributes;
|
|
9 public final Object content;
|
|
10
|
|
11 public XmlElement(String name,Map<String,String> attributes,String content) {
|
|
12 this.name = name;
|
|
13 this.attributes = attributes;
|
|
14 this.content = content;
|
|
15 }
|
|
16
|
|
17 public XmlElement(String name,Map<String,String> attributes,XmlElement[] content) {
|
|
18 this.name = name;
|
|
19 this.attributes = attributes;
|
|
20 this.content = content;
|
|
21 }
|
|
22
|
|
23 public String toString() {
|
|
24 StringBuilder sb = new StringBuilder();
|
|
25 toString(sb,0);
|
|
26 return sb.toString();
|
|
27 }
|
|
28
|
|
29 private void toString(StringBuilder sb,int indented) {
|
|
30 indent(sb,indented);
|
|
31 sb.append( '<' );
|
|
32 sb.append( name );
|
|
33 for( Map.Entry<String,String> attribute : attributes.entrySet() ) {
|
|
34 sb.append( ' ' );
|
|
35 sb.append( attribute.getKey() );
|
|
36 sb.append( "=\"" );
|
|
37 sb.append( attribute.getValue() );
|
|
38 sb.append( '"' );
|
|
39 }
|
|
40 sb.append( '>' );
|
|
41 if( content instanceof String ) {
|
|
42 String s = (String)content;
|
|
43 sb.append(s);
|
1467
|
44 } else {
|
1466
|
45 XmlElement[] elements = (XmlElement[])content;
|
|
46 sb.append( '\n' );
|
|
47 for( XmlElement element : elements ) {
|
|
48 element.toString(sb,indented+1);
|
|
49 }
|
|
50 indent(sb,indented);
|
1467
|
51 }
|
1466
|
52 sb.append( "</" );
|
|
53 sb.append( name );
|
|
54 sb.append( ">\n" );
|
|
55 }
|
|
56
|
1467
|
57 private static void indent(StringBuilder sb,int indented) {
|
1466
|
58 for( int i=0; i<indented; i++ ) {
|
|
59 sb.append('\t');
|
|
60 }
|
|
61 }
|
|
62
|
|
63 }
|