从其他文档附加子元素 [英] 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);
推荐答案
您拥有的代码将抛出关于元素来自不同文档的异常.
The code you have will throw an exception about the element being from a different document.
但是,我认为您可以使用 document1.importNode.这是文档:http://docs.oracle.com/javase/7/docs/api/org/w3c/dom/Document.html#importNode(org.w3c.dom.Node,%20boolean)
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)
这是另一个问题的示例:Java 将 XML 文档附加到现有文档
And here is an example from another question: Java appending XML docs to existing docs
这篇关于从其他文档附加子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!