在我的应用程序中,我想将一个节点从一个文档复制到另一个文档。

这是代码。

Element entryElement, operationElement;
for (int i = 0; i < eventList.getLength(); i++) {
    entryElement = (Element) eventList.item(i);
    gsTag = entryElement.getAttribute("gs_tag");
    System.out.println(gsTag);
    if (gsTag.equals("insert") || gsTag.equals("update") || gsTag.equals("delete")) {
        entryElement =  (Element) entryElement.cloneNode(true);
        rootElement.appendChild(entryElement);
        operationElement = syncDom.createElement("batch:operation");
        entryElement.appendChild(operationElement);
        operationElement.setAttribute("type", gsTag);
    }
}


在执行rootElement.appendChild(entryElement);时,发生domexception,并且我检查了异常的代码为4。在java API中,该代码意味着一个元素只能属于一个文档,但是我已经克隆了该节点。为什么会发生?

最佳答案

克隆节点不会更改其所属的文档,因为它是节点的精确副本。要将节点添加到其他文档,您需要使用Document的“ importNode”方法让目标文档“采用”它:

http://download.oracle.com/javase/1.4.2/docs/api/org/w3c/dom/Document.html#importNode%28org.w3c.dom.Node,%20boolean%29

07-24 20:20