[jdom-interest] Divorcing Root Element from document!!

Jason Hunter jhunter at acm.org
Mon Nov 13 17:04:14 PST 2000


royd at tsainc.com wrote:
> 
> I am trying to take the root element of one Document and append 
> it as a child element on a second document... I continually get 
> errors about it having a parent.  How do you divorce the root 
> element from the Document?

If you want to move an apple on one tree to another tree, what do you
do?  You remove the apple from the first tree, then add it to the second
tree.  Same as in JDOM.  

If you try to just add the apple (or Element) to the second tree or to a
new place on the tree it rightfully complains that it can't be attached
to two places.  :-)

So:

elt.getParent().removeContent(elt);  // remove
root.addContent(elt);                // add

Note that removeContent() is deprecated but I'm going to push to bring
it back.  You can also do:

elt.getParent().getChildren().remove(elt);

If you want a copy added, then you have clone() or getCopy().

-jh-



More information about the jdom-interest mailing list