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.





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


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;

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
      // Instead use this:
      Node imported = ebasket.importNode(efruit, true);

    } catch (ParserConfigurationException e) {
    } catch (IOException e) {
    } catch (SAXException e) {