Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep child tags when I get text content with DOM in Java

Tags:

java

dom

xml

tags

I am writing an XML generator in Java and I have a structure like that (I simplify it for the example):

<autocue>
     <sentence>
          <illustration>smile.jpg</illustration>
          <text>I am a <color red="255" green="0" blue="0">sentence</color> <italic>text</italic>.</text>
     </sentence>
</autocue>

I parse this kind of XML file and I works well, but when I use getTextContent() on my text node, it gives me a string like that:

I am a sentence text.

It seems logical. However, I need it to return me a string like that:

I am a <color red="255" green="0" blue="0">sentence</color> <italic>text</italic>.

Is there a simple way to get that result? Thanks in advance.

like image 794
LeGaulois88 Avatar asked Sep 30 '25 10:09

LeGaulois88


1 Answers

Instead of using getTextContent() you can use the following:

For the exact node:

getElementsByTagName("text").item(0).getNodeValue()

But if you have muliple nodes for autocue, then you can use the following:

NodeList autocueNodes = myDoc.getElementsByTagName("autocue");//here myDoc is the reference for getting document for the parser
    for (int i = 0; i < autocueNodes.getLength(); i++) {
        NodeList autocueChildNodes = autocueNodes.item(i).getChildNodes();
        if (autocueChildNodes.item(i).getLocalName() != null
                && autocueChildNodes.item(i).getLocalName().equals("sentence")) {
            NodeList sentenceList = autocueChildNodes.item(i).getChildNodes();
            for (int j = 0; j < sentenceList.getLength(); j++) {
                if (sentenceList.item(j).getLocalName() != null
                        && sentenceList.item(j).getLocalName()
                                .equals("text")) {
                    String text = sentenceList.item(j).getNodeValue();
                }
            }
        }

    }
like image 178
E Do Avatar answered Oct 02 '25 05:10

E Do



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!