[ACCEPTED]-How do I copy DOM nodes from one document to another in Java?-copy
The problem is that Node's contain a lot 15 of internal state about their context, which 14 includes their parentage and the document 13 by which they are owned. Neither adoptChild()
nor importNode()
place 12 the new node anywhere in the destination 11 document, which is why your code is failing.
Since 10 you want to copy the node and not move it 9 from one document to another there are three 8 distinct steps you need to take...
- Create the copy
- Import the copied node into the destination document
- Place the copied into it's correct position in the new document
for(Node n : nodesToCopy) {
// Create a duplicate node
Node newNode = n.cloneNode(true);
// Transfer ownership of the new node into the destination document
newDoc.adoptNode(newNode);
// Make the new node an actual item in the target document
newDoc.getDocumentElement().appendChild(newNode);
}
The Java 7 Document API allows you to combine the first 6 two operations using importNode()
.
for(Node n : nodesToCopy) {
// Create a duplicate node and transfer ownership of the
// new node into the destination document
Node newNode = newDoc.importNode(n, true);
// Make the new node an actual item in the target document
newDoc.getDocumentElement().appendChild(newNode);
}
The true
parameter on 5 cloneNode()
and importNode()
specifies whether you want a deep 4 copy, meaning to copy the node and all it's 3 children. Since 99% of the time you want 2 to copy an entire subtree, you almost always 1 want this to be true.
adoptChild does not create a duplicate, it 2 just moves the node to another parent.
You 1 probably want the cloneNode() method.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.