It very much depends on what you want to do!
If you just want to have that node in the other document you can use the importNode(...) method:
// someNode was created by another document
Node someNodeNew = doc2.importNode(someNode, true);
Now you can just add someNodeNew somewhere in doc2.
Doing this will create a copy of the old node!
If you want to move the node (including all subchilds) to another document you have 2 possibilities:
- Using the documents
adoptNode(...) method:
If it works, it will change the owner document of the node and will remove it from the old document. There's only one problem using this method:
The Javadoc states:
Attempts to adopt a node from another document to this document. If supported, it changes the owner document [...]
So this method does not have to be supported and might fail!
- The second (and in my opinion better) option:
Import the Node and then remove it out of the old tree:
// someNode was created by another document
Node someNodeNew = doc2.importNode(someNode, true);
if (someNode.getParentNode() != null)
someNode.getParentNode().removeChild(someNode);
someNode = someNodeNew ;
Document.importNode.