Tuesday, June 17, 2008

Java 1.4 get node text

The Java JRE 1.4 is missing the method org.w3c.dom.Node.getTextContent().

java.lang.NoSuchMethodError: org.w3c.dom.Node.getTextContent()

This is unfortunate, but you DO NOT have to upgrade to Java JRE 1.5! Use the function below as a replacement for getTextContent().


    /**
* Recursive implementation of the method
* org.w3c.dom.Node.getTextContent which is present in JDK 1.5 but not 1.4
* @author Tobias Hinnerup
* @param node Node that you need to get the text content of
* @return
*/

private static String getTextContent(Node node) {
Node child;
String sContent = node.getNodeValue() != null ? node.getNodeValue() : "";

NodeList nodes = node.getChildNodes();
for(int i = 0; i < nodes.getLength(); i++) {
child = nodes.item(i);
sContent += child.getNodeValue() != null ? child.getNodeValue() : "";
if(nodes.item(i).getChildNodes().getLength() > 0) {
sContent += getTextContent(nodes.item(i));
}
}

return sContent;
}

2 comments:

Anonymous said...

Thank you very much.
Works perfectly. Hate working with anything older than Java5 but sometimes you just have to.

Anonymous said...

thanks for the solution.