[jdom-interest] a small patch to protect against null nodes in DOM tree

Ed Morehouse EMorehouse at fool.com
Tue Nov 7 14:03:32 PST 2000


hello fellow jdomers,

I've had occasion to use org.jdom.input.DOMBuilder quite a bit lately and have
come across a little problem:  it seems that it is possible (in some DOM
parsers, anyway) to generate document trees containing nodes or node lists that
point to null.  I've done a little research to try to find out whether DOM says
anything about the legality of this, but haven't found an answer (if anybody
knows, please do share).  But regardless of whether it is permissible, it does
seem to happen; and DOMBuilder doesn't like it one bit.  In fact, it throws a
null-pointer-exception and dies.

I looked into this, and found that the untimely death occurs in DOMBuilder's
buildTree() method in the section commented with "Recurse on child nodes", where
the method gets the nodelist of a node's children and iterates though it,
calling itself on each node in the list.  All of this is done without checking
that the nodelist or the nodes are non-null.

This raises the question, what does a null node or nodelist mean within DOM and
how should it be treated?  In the absence of guidance from W3C, the simple
answer may be to ignore it.  In any case, in my opinion this should not be a
fatal error.

I wrote a four line patch that checks both the nodelist and each node for for
null, before trying to process it.  This seems to work quite well for my
purposes, but i am open to other solutions as well (perhaps generate null jdom
nodes to mirror the null DOM nodes...though i don't see what this would gain
you).  Anyway, please do consider the matter and discuss your thoughts.

Here's my patch against this morning's DOMBuilder:

$ diff DOMBuilder.java.original DOMBuilder.java.changed
375,376c375,380
<                 for (int i=0, size=children.getLength(); i<size; i++) {
<                     buildTree(children.item(i), doc, element, false);
---
> 		if (children != null) {
> 			for (int i=0, size=children.getLength(); i<size; i++) {
> 				if (children.item(i) != null) {
> 				    buildTree(children.item(i), doc, element, false);
> 				}
> 			}


                                  ------------
 
 - The happiest of people aren't the ones 
   who always have the best of everything;
   they are the ones who always make the best 
   of everything they have.

                                           Ed Morehouse
                                           Software Engineer/Evil Genius
                                           The Motley Fool



More information about the jdom-interest mailing list