问题是 Node 包含很多关于其上下文的内部状态,包括他们的父母身份和拥有他们的文档。既不adoptChild()
也不importNode()
将新节点放在目标文档中的任何位置,这就是您的代码失败的原因。
由于您想要复制节点而不是将其从一个文档移动到另一个文档,因此您需要采取三个不同的步骤......
- 创建副本
- 将复制的节点导入目标文档
- 将副本放在新文档中的正确位置
for(Node n : nodesToCopy) {
// Create a duplicate node
Node newNode = n.cloneNode(true);
// Transfer ownership of the new node into the destination document
newDoc.adoptNode(newNode);
// Make the new node an actual item in the target document
newDoc.getDocumentElement().appendChild(newNode);
}
Java 文档 API 允许您使用importNode()
.
for(Node n : nodesToCopy) {
// Create a duplicate node and transfer ownership of the
// new node into the destination document
Node newNode = newDoc.importNode(n, true);
// Make the new node an actual item in the target document
newDoc.getDocumentElement().appendChild(newNode);
}
true
参数 oncloneNode()
并importNode()
指定您是否需要深拷贝,即复制节点及其所有子节点。由于 99% 的时间你想要复制整个子树,你几乎总是希望这是真的。