Mercurial Hosting > luan
comparison src/goodjava/xml/XmlElement.java @ 1466:670b7d089699
xml support
| author | Franklin Schmidt <fschmidt@gmail.com> |
|---|---|
| date | Mon, 13 Apr 2020 22:00:40 -0600 |
| parents | |
| children | 509d49c493c0 |
comparison
equal
deleted
inserted
replaced
| 1465:5e3870618377 | 1466:670b7d089699 |
|---|---|
| 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); | |
| 44 } else if( content instanceof XmlElement[] ) { | |
| 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); | |
| 51 } else | |
| 52 throw new RuntimeException(); | |
| 53 sb.append( "</" ); | |
| 54 sb.append( name ); | |
| 55 sb.append( ">\n" ); | |
| 56 } | |
| 57 | |
| 58 private void indent(StringBuilder sb,int indented) { | |
| 59 for( int i=0; i<indented; i++ ) { | |
| 60 sb.append('\t'); | |
| 61 } | |
| 62 } | |
| 63 | |
| 64 } |
