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

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.