![]() |
The Java Developers Almanac 1.4 |
|
e544. Removing a Node from a DOM DocumentThis example demonstrates how to remove a single node and all nodes of a particular type. // Obtain an XML document; this method is implemented in
// e510 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>
e540. Adding a CDATA Section to a DOM Document e541. Adding a Comment to a DOM Document e542. Adding a Processing Instruction to a DOM Document e543. Adding a Text Node to a DOM Document
© 2002 Addison-Wesley. |