Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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 <code>adoptChild()</code> nor <code>importNode()</code> place the new node anywhere in the destination document, which is why your code is failing.</p> <p>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...</p> <ol> <li>Create the copy</li> <li>Import the copied node into the destination document</li> <li>Place the copied into it's correct position in the new document</li> </ol> <pre> 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); } </pre> <p>The Java Document API allows you to combine the first two operations using <code>importNode()</code>.</p> <pre> 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); } </pre> <p>The <code>true</code> parameter on <code>cloneNode()</code> and <code>importNode()</code> 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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload