You need to call detach()
on the node you want to move. From the dom4j JavaDocs
Node node = ...;
Element someOtherElement = ...;
someOtherElement.add( node.detach() );
Since Element
implements Node
if you need to convert back to Element
you can do it just by casting (provided you know that the thing you detached was an Element
). Another option for you might be to copy the Element
. Using your code as a starting point:
Element moduleRootElement = doc.addElement("Request");
if (rootElement.getName().equals("someName") {
moduleRootElement.add(childElement.getName());
} else {
moduleRootElement.add(rootElement.createCopy());
}
It looks like you actually tried this, but didn't quite get all the way there. Remember, in java using =
reassigns the variable to the new object. All the existing references to it are broken.
As a side note, you probably also need to check your root element's name with
if(rootElement.getName().equals("someName"))
instead of using ==