[jdom-interest] detach() [eg]

Jason Hunter jhunter at acm.org
Wed Apr 25 13:32:09 PDT 2001

Patrick Dowler wrote:
> Moving an element is:
>    el.getParent().removeContent( el ); // ignoring boolean return
>    newParent.addContent( el );

You should never write that code.  You'll get a NullPointerException if
the parent is null, which happens if the elt is a root or (more
commonly) if the elt is just unattached at the moment.  The *real* code
to handle a move is ugly without detach().

> Personally, is it really all that bad to use setRootElement() instead of detach()?
>    Element oldRoot = doc.getRootElement();
>    doc.setRootElement( new Element("junk") );
> So, you have to create a single Element that is otherwise wasted. 

It's not wasting an object.  It's that without detach() you have to do a
lot of special casing depending on if the elt is:
1) attached to a doc -- call setRootElement() on another
2) attached to an elt -- call getParent().removeContent()
3) attached to nothing -- know to call nothing or risk NPE


More information about the jdom-interest mailing list