[jdom-interest] How to check for whether an element has children.

Ian Lea ian.lea at blackwell.co.uk
Thu Dec 27 06:02:58 PST 2001


As you say c does have children, "oid" and "name", but c doesn't
have a child "object" hence n = c.getChild("object") returns null,
and s = n.hasChildren throws NPE.  I think you either need to
check for n == null or use the List methods.

--
Ian.
ian.lea at blackwell.co.uk


"Nott, Matthias" wrote:
> 
> Y'all,
> 
> Sorry for the newbie question, but why does the following
> code result in a null pointer?
> 
>         String myXML =
> 
> "<object><oid>4711</oid><name>page</name><object><oid>4712</oid><name>child1
> </name></object><object><oid>4713</oid><name>child2</name></object></object>
> ";
> 
>         Document tXML = new SAXBuilder().build(new StringReader(myXML));
>         Element e = tXML.getRootElement();
>         Element c = e.getChild("object");
>         Element n = c.getChild("object");
>         boolean s = n.hasChildren();
> 
>         out.println("<xmp>"+s+"</xmp>");
> 
> If I say, s = c.hasChildren(); I get true, as this is object oid 4712 which
> has children oid and name. I would have expected to s = n.hasChildren() to
> return false, but not a null pointer. The same error appears if I try to
> String s = n.getChildren().toString();
> 
> So how can I check without getting an exception for whether an element
> still has children? I can convert it to a list and then check out the
> index for the <object> element, but I am a bit afraid I might be loosing
> performance here.
> 
> Thanks
> 
> Matthias



More information about the jdom-interest mailing list