I'm having trouble with copying nodes from one document to another one. I've used both the adoptNode and importNode methods from Node but they don't work. I've also tried appendChild but that throws an exception. I'm using Xerces. Is this not implemented there? Is there another way to do this?
List<Node> nodesToCopy = ...;
Document newDoc = ...;
for(Node n : nodesToCopy) {
// this doesn't work
newDoc.adoptChild(n);
// neither does this
//newDoc.importNode(n, true);
}
Best Solution
The problem is that Node's contain a lot of internal state about their context, which includes their parentage and the document by which they are owned. Neither
adoptChild()
norimportNode()
place the new node anywhere in the destination document, which is why your code is failing.Since you want to copy the node and not move it from one document to another there are three distinct steps you need to take...
The Java Document API allows you to combine the first two operations using
importNode()
.The
true
parameter oncloneNode()
andimportNode()
specifies whether you want a deep copy, meaning to copy the node and all it's children. Since 99% of the time you want to copy an entire subtree, you almost always want this to be true.