The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > org.w3c.dom  [30 examples] > Text Nodes  [3 examples]

e547. Merging Text Nodes in a DOM Document

This example removes an element node and inserts its children nodes into the element node's parent. This can cause two text nodes to be adjacent. Normalizing the document merges adjacent text nodes into one and removes empty text nodes.
    // Obtain a 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 the root element to remove
    Element element = (Element)doc.getElementsByTagName("b").item(0);
    
    // Get the parent of the element
    Node parent = element.getParentNode();
    
    // Move all children of the element in front of the element
    while (element.hasChildNodes()) {
        parent.insertBefore(element.getFirstChild(), element);
    }
    
    // Remove the element
    parent.removeChild(element);
    
    // Merge all text nodes under the parent
    parent.normalize();
This is the sample input for the example:
    <?xml version="1.0" encoding="UTF-8"?>
    <root>
        Here is <b>some</b> text
    </root>
This is the resulting XML:
    <?xml version="1.0" encoding="UTF-8"?>
    <root>
        Here is some text
    </root>

 Related Examples
e545. Editing Text in a CDATA, Comment, and Text Node of a DOM Document
e546. Splitting a Text Node in a DOM Document

See also: Adding and Removing Nodes    Element Attributes    Elements    Getting Nodes    XPath   


© 2002 Addison-Wesley.