Showing posts with label java 1.4 get node text. Show all posts
Showing posts with label java 1.4 get node text. Show all posts

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;
}