xml – Converting getNodeValue to a string – Education Career Blog

I asked a question here yesterday and it was kindly answered. However, I have taken the sample code and attempted to print out the value of the current node, i.e. using getNodeValue.

Whenever I run the jsp it returns a “org.apache.jasper.JasperException: An exception occurred processing JSP page” error on “printOut = n.getNodeValue().trim();”

Below is my edited code from dogbane

String  = "tagToFind";
String printOut = "";
Node n = aNode.getParentNode();
while (n != null && !n.getNodeName().equals(tagToFind)) { 
n = n.getParentNode();
printOut = n.getNodeValue();
}
out.println(printOut);

,

It could be that getNodeValue is returning null, causing the .trim() part to throw a NullPointerException.

getNodeValue returns null for all node types except text, attribute, comment, processing instruction and CDATA. Note that elements and documents return null for getNodeValue. You are walking up the node tree so you are going to hit one of those very quickly.

You can fix this by just checking for a null value before attempting to trim it.

,

In addition to @Cameron’s answer you should be aware of a flaw in the logic of your loop.

You first change n to point to the parent, and then use getNodeValue() on it.

But n could have become null from the .getParentNode() call.

Try swapping them..

printOut = n.getNodeValue();
n = n.getParentNode();

Leave a Comment