Append element to a DOM tree in Java
Description
The following code shows how to append element to a DOM tree.
Example
//from ww w . j a va 2 s . c o m
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import org.xml.sax.InputSource;
public class Main {
static public void main(String[] arg) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(true);
dbf.setNamespaceAware(true);
dbf.setIgnoringElementContentWhitespace(true);
DocumentBuilder builder = dbf.newDocumentBuilder();
StringReader sr = new StringReader("<tag>java2s.com</tag>");
Document document = builder.parse(new InputSource(sr));
append(document, "newName", "java2s.com", "newEmail");
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
StringWriter sw = new StringWriter();
trans.transform(new DOMSource(document), new StreamResult(sw));
System.out.println(sw.toString());
}
public static void append(Document doc, String name, String phone, String email) {
Element personNode = doc.createElement("person");
Element nameNode = doc.createElement("name");
personNode.appendChild(nameNode);
Text nametextNode = doc.createTextNode(name);
nameNode.appendChild(nametextNode);
Element phoneNode = doc.createElement("phone");
personNode.appendChild(phoneNode);
Text phonetextNode = doc.createTextNode(phone);
phoneNode.appendChild(phonetextNode);
Element emailNode = doc.createElement("email");
personNode.appendChild(emailNode);
Text emailtextNode = doc.createTextNode(email);
emailNode.appendChild(emailtextNode);
Element root = doc.getDocumentElement();
root.appendChild(personNode);
}
}