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.
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();
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With