Element.java

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