f



Empty text node throws NullPointerException

I have a line of code like this: 

String textnode = node.getFirstChild().getNodeValue();

It works fine for: 

<MyElement>MyValue</MyElement>

But throws NullPointerException for: 

<MyElement></MyElement>

Yet the latter case is OK in my business logic - I don't want to
throw, I want to continue parsing. Is there a way to test before the
exception, or simply return a null value to my textnode String above?

iksrazal
0
iksrazal (292)
5/11/2004 10:00:02 PM
comp.lang.java.programmer 52714 articles. 1 followers. Post Follow

3 Replies
259 Views

Similar Articles

[PageSpeed] 40

"iksrazal" <iksrazal@terra.com.br>
> I have a line of code like this:
>
> String textnode = node.getFirstChild().getNodeValue();
>
> It works fine for:
>
> <MyElement>MyValue</MyElement>
>
> But throws NullPointerException for:
>
> <MyElement></MyElement>
>
> Yet the latter case is OK in my business logic - I don't want to
> throw, I want to continue parsing. Is there a way to test before the
> exception, or simply return a null value to my textnode String above?
>
> iksrazal

You can test which var. return null (see your exceptions trace for help)
or
add another nested block to handle this null exception ( by doing nothing or
whatever)

--
Song

More info.:
http://www.dcs.warwick.ac.uk/~esubbn/


0
tips1 (87)
5/11/2004 10:29:42 PM
iksrazal wrote:
> I have a line of code like this: 
> 
> String textnode = node.getFirstChild().getNodeValue();
> 
> It works fine for: 
> 
> <MyElement>MyValue</MyElement>
> 
> But throws NullPointerException for: 
> 
> <MyElement></MyElement>

That's because node.getFirstChild() is going to be null if there
are no child nodes, right? Another way to go might be this:

NodeList children = node.getChildNodes();
if( ( children != null ) && ( children.getLength() > 0 ) ) {
     // children.item( 0 ) is the first child
     // be sure to check nodeType before presuming
     // org.w3c.dom.Node.TEXT_NODE
}

0
bitbucket44 (1435)
5/12/2004 5:12:48 AM
iksrazal wrote:
> I have a line of code like this: 
> 
> String textnode = node.getFirstChild().getNodeValue();
> 
> It works fine for: 
> 
> <MyElement>MyValue</MyElement>
> 
> But throws NullPointerException for: 
> 
> <MyElement></MyElement>

Right, because there is no first child.  Hence, the getFirstChild() call 
returns null, and you immediately attempt to dereference the null 
result.  Try:

    Node firstChild = node.getFirstChild();
    String textnode;
    if (firstChild == null) textnode = null;
    else textnode = firstChild.getNodeValue();

-- 
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
0
cdsmith (3862)
5/13/2004 6:40:00 PM
Reply: