Dom4j Detach/Copy node from one xml and add to another

dom4j, java

Solution

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 `==`

Problem

I am actually traversing `src` xml and converting it into another `destination` xml. But part of `src` xml will be just copied and added to the `destination`. But when I am trying to do that I am getting following Exception: ``` could not be added to the element "<DestinationParent>" because: The Node already has an existing parent of "<SourceParent" ``` I am traversing src XML and calling this function Code ``` private static Element treeWalk (Element rootElement, Element parentElement) { Element moduleRootElement = doc.addElement("Request"); if(rootElement.getName()=="someName") { moduleRootElement.add(childElement.getName()); } else { moduleRootElement.add(rootElement); //If root's parent is not null I get a exception here. //moduleRootElement= rootElement.createCopy(); //Didn't work } } ```

Original source