Removing a Node from a DOM Document - Java XML

Java examples for XML:DOM

Description

Removing a Node from a DOM Document

Demo Code


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
  public static void main(String[] args) throws Exception {
    Document doc = null;/*from  w ww.  j a v  a  2s  .com*/

    // Obtain a node
    Element element = (Element) doc.getElementsByTagName("junk").item(0);

    // Remove the node
    element.getParentNode().removeChild(element);

    // Remove all <junk> elements
    removeAll(doc, Node.ELEMENT_NODE, "junk");

    // Remove all comment nodes
    removeAll(doc, Node.COMMENT_NODE, null);

    // Normalize the DOM tree to combine all adjacent text nodes
    doc.normalize();
  }

  public static void removeAll(Node node, short nodeType, String name) {
    if (node.getNodeType() == nodeType
        && (name == null || node.getNodeName().equals(name))) {
      node.getParentNode().removeChild(node);
    } else {
      // Visit the children
      NodeList list = node.getChildNodes();
      for (int i = 0; i < list.getLength(); i++) {
        removeAll(list.item(i), nodeType, name);
      }
    }
  }
}

Related Tutorials