[jdom-interest] Moving elements

Jason Hunter jhunter at servlets.com
Wed Apr 30 18:55:42 PDT 2003


Two things that frequently bite people are:

a) Moving a set of content from one element to another, because making
sure the content is free of its original parentage is tricky.

b) Sorting or otherwise reordering a set of content, because sorting
algorithms can, during the "swap", add content before removing content
which we don't allow because of parentage.

I'd like to make sure we resolve these issues, so let's brainstorm how
to do it:


1) There's a trick Alex figured out given the current code where you
create a second list to retain the content list, detach the content from
its parent with a semi-secret setContent(null) call, then use the
retained list:

Instead of:

      List anchorList = anchor.getContent();
      heading.setContent(anchorList);

do this:

      List anchorList = new ArrayList(anchor.getContent());
      anchor.setContent(null);
      heading.setContent(anchorList);

This of course is something more creative and innovative than several US
patents issued lately, and while it works, it's not something I want to
require people to use.  :-)


2) We could have a new method like this on Element and Document:

  List element.getContentDetached()

It would return a list of the detached content.  Then you could do this:

heading.setContent(anchorList.getContentDetached());

Not bad, and easy to find by scanning the Javadocs.  For sorting you'll
have to make sure to sort on the detached list.


3) We could change the add semantics.  David Flanagan suggested this,
and it's how DOM does things.  If you add an element somewhere and the
element already has a parent, the new parent just trumps it.  Compare
that to right now we throw an IllegalAddException.  If we changed
behaviors, it would make nice code:

heading.setContent(anchorList.getContent());

Sorting works naturally also.  The big issue is whether you expect this
sort of auto-detachment.  I guess I wouldn't, but maybe I've used JDOM
too long.  :-)


4) Something else?


-jh-



More information about the jdom-interest mailing list