Adding a Node to a DOM Document - Java XML

Java examples for XML:DOM

Description

Adding a Node to a DOM Document

Demo Code

import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Main {
  public void m() throws Exception {
    Document doc = null;//from w ww. j  a v  a2s.c o m
    // Insert the root element node
    Element element = doc.createElement("root");
    doc.appendChild(element);

    // Insert a comment in front of the element node
    Comment comment = doc.createComment("a comment");
    doc.insertBefore(comment, element);

    // Add a text node to the element
    element.appendChild(doc.createTextNode("D"));

    // Add a text node to the beginning of the element
    element.insertBefore(doc.createTextNode("A"), element.getFirstChild());

    // Add a text node before the last child of the element
    element.insertBefore(doc.createTextNode("java2s.com"), element.getLastChild());

    // Add another element after the first child of the root element
    Element element2 = doc.createElement("item");
    element.insertBefore(element2, element.getFirstChild().getNextSibling());

    // Add a text node in front of the new item element
    element2.getParentNode().insertBefore(doc.createTextNode("B"), element2);
  }
}

Related Tutorials