Removing a Node from a DOM Document

This example demonstrates how to remove a single node and all nodes of a particular type.
// Obtain an XML document; this method is implemented in // The Quintessential Program to Create a DOM Document from an XML File Document doc = parseXmlFile("infilename.xml", false); // 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(); // This method walks the document and removes all nodes // of the specified type and specified name. // If name is null, then the node is removed if the type matches. 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); } } }
This is the sample input for the example:
<?xml version="1.0" encoding="UTF-8"?> <root> <!--comment1--> <elem>a</elem> <junk>b</junk> <elem> <!--comment2--> <junk>c<junk>d</junk></junk> </elem> <!--comment3--> <junk>e</junk> </root>
This is the resulting XML:
<?xml version="1.0" encoding="UTF-8"?> <root> <elem>a</elem> <elem> </elem> </root>

Comments

15 Jun 2010 - 4:54am by Anonymous (not verified)

nice

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.