Copying a Subtree of Nodes from One DOM Document to Another

When copying a subtree of nodes from one document to another, cloning the subtree and then inserting it into the other document will result in a wrong document exception. The subtree of nodes must be imported into the other document using importNode().
// Obtain an element in one document; the following method is implemented in // The Quintessential Program to Create a DOM Document from an XML File Document doc1 = parseXmlFile("infilename1.xml", false); NodeList list = doc1.getElementsByTagName("entry"); Element element = (Element)list.item(0); // Create another document Document doc2 = parseXmlFile("infilename2.xml", false); // Make a copy of the element subtree suitable for inserting into doc2 Node dup = doc2.importNode(element, true); // Insert the copy into doc2 doc2.getDocumentElement().appendChild(dup);

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.