Element.java

 1package de.gultsch.chat.xml;
 2
 3import java.util.ArrayList;
 4import java.util.Hashtable;
 5import java.util.List;
 6
 7public class Element {
 8	protected String name;
 9	protected Hashtable<String, String> attributes = new Hashtable<String, String>();
10	protected String content;
11	protected List<Element> children = new ArrayList<Element>();
12	
13	public Element(String name) {
14		this.name = name;
15	}
16	
17	public Element addChild(Element child) {
18		this.content = null;
19		children.add(child);
20		return this;
21	}
22	
23	public Element setContent(String content) {
24		this.content = content;
25		this.children.clear();
26		return this;
27	}
28	
29	public Element setAttribute(String name, String value) {
30		this.attributes.put(name, value);
31		return this;
32	}
33	
34	public Element setAttributes(Hashtable<String, String> attributes) {
35		this.attributes = attributes;
36		return this;
37	}
38	
39	public String toString() {
40		StringBuilder elementOutput = new StringBuilder();
41		if ((content==null)&&(children.size() == 0)) {
42			Tag emptyTag = Tag.empty(name);
43			emptyTag.setAtttributes(this.attributes);
44			elementOutput.append(emptyTag.toString());
45		} else {
46			Tag startTag = Tag.start(name);
47			startTag.setAtttributes(this.attributes);
48			elementOutput.append(startTag);
49			if (content!=null) {
50				elementOutput.append(content);
51			} else {
52				for(Element child : children) {
53					elementOutput.append(child.toString());
54				}
55			}
56			Tag endTag = Tag.end(name);
57			elementOutput.append(endTag);
58		}
59		return elementOutput.toString();
60	}
61
62	public String getName() {
63		return name;
64	}
65}