view src/goodjava/xml/XmlElement.java @ 1467:509d49c493c0

minor
author Franklin Schmidt <fschmidt@gmail.com>
date Mon, 13 Apr 2020 22:16:59 -0600
parents 670b7d089699
children 35f3bfd4f51d
line wrap: on
line source

package goodjava.xml;

import java.util.Map;


public final class XmlElement {
	public final String name;
	public final Map<String,String> attributes;
	public final Object content;

	public XmlElement(String name,Map<String,String> attributes,String content) {
		this.name = name;
		this.attributes = attributes;
		this.content = content;
	}

	public XmlElement(String name,Map<String,String> attributes,XmlElement[] content) {
		this.name = name;
		this.attributes = attributes;
		this.content = content;
	}

	public String toString() {
		StringBuilder sb = new StringBuilder();
		toString(sb,0);
		return sb.toString();
	}

	private void toString(StringBuilder sb,int indented) {
		indent(sb,indented);
		sb.append( '<' );
		sb.append( name );
		for( Map.Entry<String,String> attribute : attributes.entrySet() ) {
			sb.append( ' ' );
			sb.append( attribute.getKey() );
			sb.append( "=\"" );
			sb.append( attribute.getValue() );
			sb.append( '"' );
		}
		sb.append( '>' );
		if( content instanceof String ) {
			String s = (String)content;
			sb.append(s);
		} else {
			XmlElement[] elements = (XmlElement[])content;
			sb.append( '\n' );
			for( XmlElement element : elements ) {
				element.toString(sb,indented+1);
			}
			indent(sb,indented);
		}
		sb.append( "</" );
		sb.append( name );
		sb.append( ">\n" );
	}

	private static void indent(StringBuilder sb,int indented) {
		for( int i=0; i<indented; i++ ) {
			sb.append('\t');
		}
	}

}