The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > org.w3c.dom  [30 examples] > Adding and Removing Nodes  [6 examples]

e544. 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
    // 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>

 Related Examples
e539. Adding a Node to a DOM Document
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

See also: Element Attributes    Elements    Getting Nodes    Text Nodes    XPath   


© 2002 Addison-Wesley.