문제

For example i have html content like this.

<div>go to the text from here.<br> from there <br> Go to the text</div>

In the above content, i want to insert span tag for the word alone Like the below output using java.

I'm using org.w3c.dom package.

I tried but not able to make success

Element e = doc.createElement("span");
String text = preElement.getTextContent();
if(text.indexOf("text"){
e.setTextContent("text");
}
// Afterwards how to insert this to document. How to use insertBefore method for the //inbetween text.

Expected Output:

<div>go to the <span>text</span> from here.<br> from there <br> Go to the <span>text</span></div>

Please help.

도움이 되었습니까?

해결책

You have to use the splitText method on your text node to split it into three nodes, isolating the word you need to wrap in your element. Then you only have to replace the text node you just isolated (use replaceChild) with the new element. There is no need to create a new text node, you can simply put the one you removed in the element you added.

Java implementation reference: http://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Text.html#splitText%28int%29 http://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Node.html#replaceChild%28org.w3c.dom.Node,%20org.w3c.dom.Node%29.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top