Insert element to a DOM tree in Java

Description

The following code shows how to insert element to a DOM tree.

Example


import java.io.StringReader;
import java.io.StringWriter;
/*w  w  w.ja  v  a 2s.  co m*/
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.Node;
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));
    insert(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 insert(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();
    Node firstChildNode = root.getFirstChild();
    root.insertBefore(personNode, firstChildNode);
  }
}




















Home »
  Java Tutorial »
    XML »




DOM
SAX