gpt4 book ai didi

java - 如何在不出现 DOMException 的情况下将节点复制到不同的文档?

转载 作者:行者123 更新时间:2023-12-02 08:13:30 28 4
gpt4 key购买 nike

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

这是代码。

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

关于java - 如何在不出现 DOMException 的情况下将节点复制到不同的文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6893455/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com