Namek
Namek

Reputation: 487

Working with XML in Java - DOM

My input XML is:

<ROOT>
    <Child_1>
        <Child_1_1>
            <Child_1_1>
                <p>test123 test456 test789 test101112</p>
            </Child_1_1>
        </Child_1_1>
    </Child_1>
</ROOT>

I wanted to manipulate, that let say, after 23 char in my paragraph, I wanted to split my text to two (or more if there are multiple 23 char occurs) paragraphs, so let say:

<ROOT>
    <Child_1>
        <Child_1_1>
            <Child_1_1>
                <p>test123 test456 test789</p><p>test101112</p>
            </Child_1_1>
        </Child_1_1>
    </Child_1>
</ROOT>

In Java code, I'm using W3C DOM:

NodeList nodeListXml = documentXml.getElementsByTagName("p");
for (int i = 0; i < nodeListXml.getLength(); i++) {
    Element elementXml = (Element) nodeListXml.item(i);
    String unformattedText = elementXml.getTextContent();
    String formattedText;

    //some logic to split text
    //...
    //some logic to split text

    //here "formattedText" value is "test123 test456 test789</p><p>test101112" as expected
    elementXml.setTextContent(formattedText);
}

After that, my "documentXml" contains incorrect value:

<ROOT>
    <Child_1>
        <Child_1_1>
            <Child_1_1>
                <p>test123 test456 test789&lt;/p&gt;&lt;p&gt;test101112</p>
            </Child_1_1>
        </Child_1_1>
    </Child_1>
</ROOT>

And my logic is somehow not working, because of those escaped entities. How can I fix it?

Upvotes: 1

Views: 83

Answers (1)

VDanyliuk
VDanyliuk

Reputation: 1049

try something like this :

String[] afterSplit =  unformattedText.split("")//you split logic
for(String text : afterSplit){
    Element element = documentXml.createElement("p");
    element.setTextContent(text);
    elementXml.appendChild(element);
}

Upvotes: 1

Related Questions