📄 e546. splitting a text node in a dom document.txt
字号:
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
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -