1 package de.timroes.axmlrpc.xmlcreator; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 /** 7 * An xml element within an xml tree. 8 * In this case an xml element can have a text content OR a multiple amount 9 * of children. The xml element itself has a name. 10 * 11 * @author Tim Roes 12 */ 13 public class XmlElement { 14 15 private List<XmlElement> children = new ArrayList<XmlElement>(); 16 private String name; 17 private String content; 18 19 /** 20 * Create a new xml element with the given name. 21 * 22 * @param name The name of the xml element. 23 */ XmlElement(String name)24 public XmlElement(String name) { 25 this.name = name; 26 } 27 28 /** 29 * Add a child to this xml element. 30 * 31 * @param element The child to add. 32 */ addChildren(XmlElement element)33 public void addChildren(XmlElement element) { 34 children.add(element); 35 } 36 37 /** 38 * Set the content of this xml tag. If the content is set the children 39 * won't be used in a string representation. 40 * 41 * @param content Content of the xml element. 42 */ setContent(String content)43 public void setContent(String content) { 44 this.content = content; 45 } 46 47 /** 48 * Return a string representation of this xml element. 49 * 50 * @return String representation of xml element. 51 */ 52 @Override toString()53 public String toString() { 54 StringBuilder builder = new StringBuilder(); 55 if(content != null && content.length() > 0) { 56 builder.append("\n<").append(name).append(">") 57 .append(content) 58 .append("</").append(name).append(">\n"); 59 return builder.toString(); 60 } else if(children.size() > 0) { 61 builder.append("\n<").append(name).append(">"); 62 for(XmlElement x : children) { 63 builder.append(x.toString()); 64 } 65 builder.append("</").append(name).append(">\n"); 66 return builder.toString(); 67 } else { 68 builder.append("\n<").append(name).append("/>\n"); 69 return builder.toString(); 70 } 71 } 72 73 } 74