Merging nodes from different Documents.

Published: Wednesday, 18 August 2004

org.w3c.dom.DOMException: WRONG_DOCUMENT_ERR: A node is used in a different document than the one that created it

I received the above error when I had created two documents, and wanted to create a third by merging the 1st and the 2nd together.

basket.xml:

<basket></basket>

apple.xml:

<fruit>apple</fruit>

We would like to put the apple into the basket so the new xml document will look like:

<basket>
  <fruit>apple</fruit>
</basket>

Example code and comments are below

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

public class MergeExample {
  public static void main(String args[]) {
    try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db;
      db = dbf.newDocumentBuilder();
      Document doc_basket = db.parse("file:///basket.xml");
      Document doc_fruit = db.parse("file:///apple.xml");
      // Assume the first child is an Element.
      Element ebasket = (Element) doc_basket.getFirstChild();
      Element efruit = (Element) doc_fruit.getFirstChild();
      // now try to add fruit to the basket.
      
      
      // The next line will raise the exception
      ebasket.appendChild(efruit.cloneNode(true));
      
      // Instead use this:
      Node imported = ebasket.importNode(efruit, true);
      ebasket.appendChild(imported);

    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    }
  }
}