I wan't to parse a xml with java that looks something like this:
<sentence>This is a <a><b>long</b></a> sentence.</sentence>
<sentence>This is a second <a><b>even</b></a> longer sentence.</sentence>
As a result i need the whole sentence without the xml. I tried to parse this with dom4j. Calling the function element.getText() (current element is the sentence tag) i just get the sentence without the text in the nested xml tags.
Thanks for your help! Regards
将数据保留在xml标记的[CDATA]部分中
<sentence><![CDATA[This is a <a><b>long</b></a> sentence.]]></sentence>
You can use XPath to select all the text nodes
String getAllTextContent(Node node) {
List<Node> nodes = node.selectNodes("descendant-or-self::text()");
StringBuilder buf = new StringBuilder();
for ( Node n : nodes ) {
buf.append(n.getText());
}
return buf.toString();
}
// usage
System.out.println(getAllTextContent(doc.selectSingleNode("//sentence")));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.