diff src/goodjava/xml/XmlElement.java @ 1468:35f3bfd4f51d

xml
author Franklin Schmidt <fschmidt@gmail.com>
date Tue, 14 Apr 2020 08:44:33 -0600
parents 509d49c493c0
children 21f5edab1fbf
line wrap: on
line diff
--- a/src/goodjava/xml/XmlElement.java	Mon Apr 13 22:16:59 2020 -0600
+++ b/src/goodjava/xml/XmlElement.java	Tue Apr 14 08:44:33 2020 -0600
@@ -8,13 +8,25 @@
 	public final Map<String,String> attributes;
 	public final Object content;
 
+	public XmlElement(String name,Map<String,String> attributes) {
+		this.name = name;
+		this.attributes = attributes;
+		this.content = null;
+	}
+
 	public XmlElement(String name,Map<String,String> attributes,String content) {
+		if( content == null )
+			throw new IllegalArgumentException("content can't be null");
 		this.name = name;
 		this.attributes = attributes;
 		this.content = content;
 	}
 
 	public XmlElement(String name,Map<String,String> attributes,XmlElement[] content) {
+		if( content == null )
+			throw new IllegalArgumentException("content can't be null");
+		if( content.length == 0 )
+			throw new IllegalArgumentException("content can't be empty");
 		this.name = name;
 		this.attributes = attributes;
 		this.content = content;
@@ -34,21 +46,29 @@
 			sb.append( ' ' );
 			sb.append( attribute.getKey() );
 			sb.append( "=\"" );
-			sb.append( attribute.getValue() );
+			sb.append( encode(attribute.getValue()) );
 			sb.append( '"' );
 		}
-		sb.append( '>' );
-		if( content instanceof String ) {
+		if( content == null ) {
+			sb.append( "/>\n" );
+		} else if( content instanceof String ) {
+			sb.append( '>' );
 			String s = (String)content;
-			sb.append(s);
+			sb.append( encode(s) );
+			closeTag(sb,name);
 		} else {
+			sb.append( '>' );
 			XmlElement[] elements = (XmlElement[])content;
 			sb.append( '\n' );
 			for( XmlElement element : elements ) {
 				element.toString(sb,indented+1);
 			}
 			indent(sb,indented);
+			closeTag(sb,name);
 		}
+	}
+
+	private static void closeTag(StringBuilder sb,String name) {
 		sb.append( "</" );
 		sb.append( name );
 		sb.append( ">\n" );
@@ -60,4 +80,29 @@
 		}
 	}
 
+	private static String encode(String s) {
+		final char[] a = s.toCharArray();
+		StringBuilder buf = new StringBuilder();
+		for( int i=0; i<a.length; i++ ) {
+			char c = a[i];
+			switch(c) {
+			case '&':
+				buf.append("&amp;");
+				break;
+			case '<':
+				buf.append("&lt;");
+				break;
+			case '>':
+				buf.append("&gt;");
+				break;
+			case '"':
+				buf.append("&quot;");
+				break;
+			default:
+				buf.append(c);
+			}
+		}
+		return buf.toString();
+	}
+
 }