Element.java

  1package eu.siacs.conversations.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 findChild(String name) {
 30		for(Element child : this.children) {
 31			if (child.getName().equals(name)) {
 32				return child;
 33			}
 34		}
 35		return null;
 36	}
 37	
 38	public boolean hasChild(String name) {
 39		for(Element child : this.children) {
 40			if (child.getName().equals(name)) {
 41				return true;
 42			}
 43		}
 44		return false;
 45	}
 46	
 47	public List<Element> getChildren() {
 48		return this.children;
 49	}
 50	
 51	public String getContent() {
 52		return content;
 53	}
 54	
 55	public Element setAttribute(String name, String value) {
 56		this.attributes.put(name, value);
 57		return this;
 58	}
 59	
 60	public Element setAttributes(Hashtable<String, String> attributes) {
 61		this.attributes = attributes;
 62		return this;
 63	}
 64	
 65	public String getAttribute(String name) {
 66		if (this.attributes.containsKey(name)) {
 67			return this.attributes.get(name);
 68		} else {
 69			return null;
 70		}
 71	}
 72	
 73	public String toString() {
 74		StringBuilder elementOutput = new StringBuilder();
 75		if ((content==null)&&(children.size() == 0)) {
 76			Tag emptyTag = Tag.empty(name);
 77			emptyTag.setAtttributes(this.attributes);
 78			elementOutput.append(emptyTag.toString());
 79		} else {
 80			Tag startTag = Tag.start(name);
 81			startTag.setAtttributes(this.attributes);
 82			elementOutput.append(startTag);
 83			if (content!=null) {
 84				elementOutput.append(encodeEntities(content));
 85			} else {
 86				for(Element child : children) {
 87					elementOutput.append(child.toString());
 88				}
 89			}
 90			Tag endTag = Tag.end(name);
 91			elementOutput.append(endTag);
 92		}
 93		return elementOutput.toString();
 94	}
 95
 96	public String getName() {
 97		return name;
 98	}
 99	
100	private String encodeEntities(String content) {
101		content = content.replace("&","&amp;");
102		content = content.replace("<","&lt;");
103		content = content.replace(">","&gt;");
104		content = content.replace("\"","&quot;");
105		content = content.replace("'","&apos;");
106		return content;
107	}
108}