Search code examples
javaxmlw3c

Appending child element from other document


In my program i have to create some document creator and I want to split functionality of creating elements into several classes. Each class will create a single element and main creator will extract that element via interface and attach to body.

The thing is that i don't want to pass any arguments into constructors call e.g.

    creator.createDocument()
        .setDocumentHeader(
             new DocumentHeader()
                 .setSomeValue(41)
             )

To simplify the problem lets say that I have a code

import org.w3c.dom.Document;
import org.w3c.dom.Element;

DocumentBuilderFactory dbfac1 = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder1 = dbfac1.newDocumentBuilder();
Document document1 = docBuilder1.newDocument();

DocumentBuilderFactory dbfac2 = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder2 = dbfac2.newDocumentBuilder();
Document document2 = docBuilder2.newDocument();

Element elementFromDoc1 = document1.createElement("body");
Element elementFromDoc2 = document2.createElement("someElement");

The question is, is that legal to do the following operation?

elementFromDoc1.appendChild(elementFromDoc2);

Solution

  • The code you have will throw an exception about the element being from a different document.

    However, you can use document1.importNode I think. Here is the documentation: http://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Document.html#importNode(org.w3c.dom.Node,%20boolean)

    And here is an example from another question: Java appending XML docs to existing docs