tags:

views:

24

answers:

2

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);
+1  A: 

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.

Cameron Skinner
Thank you, that's a good tip but I tried adding an if (n != null) {printOut = n.getNodeValue().trim();} but I still get the same error
Hammer
The problem is not that n == null, it's that n.getNodeValue() == null. Try testing for that.
Cameron Skinner
A: 

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();
Gaby
The idea is print out the value for "tagToFind"... Which should be 1 in front of the current Node, hence it needs to go after the 'getParentNode'. Otherwise it would always print the Node just after "tagToFind", which is one before the one I'm after. Does that make sense?
Hammer
@Hammer the `printOut = .. ` should not even be in the loop.. The condition to enter the loop is that n is not null and that n is not the tag you want. Once n becomes null or points to the tag you want it will skip the loop. and thus the code right after it can use the n (null or tagToFin) and print its contents..
Gaby