The Java Developers Almanac 1.4


Order this book from Amazon.

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

e546. Splitting a Text Node in a DOM Document

This example wraps a substring in an element. This requires breaking a text node in two places and then replacing the middle text node with an element node.
    // 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
    Element element = doc.getDocumentElement();
    
    // Get the text node
    Text text1 = (Text)element.getFirstChild();
    String string = text1.getData();
    
    // Split the node at the beginning of the word
    String word = "some";
    Text text2 = text1.splitText(string.indexOf(word));
    
    // Split the new text node at the end of the word
    Text text3 = text2.splitText(word.length());
    
    // Create a new element and move the middle text node to it
    Element newElement = doc.createElement("b");
    newElement.appendChild(text2);
    
    // Insert the new element where the middle node used to be
    element.insertBefore(newElement, text3);
This is the sample input for the example:
    <?xml version="1.0" encoding="UTF-8"?>
    <root>
        Here is some text
    </root>
This is the resulting XML:
    <?xml version="1.0" encoding="UTF-8"?>
    <root>
        Here is <b>some</b> text
    </root>

 Related Examples
e545. Editing Text in a CDATA, Comment, and Text Node of a DOM Document
e547. Merging Text Nodes in a DOM Document

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


© 2002 Addison-Wesley.