Appending child element from other document

蹲街弑〆低调 提交于 2020-01-16 05:12:13

问题


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);

回答1:


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



来源:https://stackoverflow.com/questions/25543588/appending-child-element-from-other-document

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!