问题在于,节点的上下文包含许多内部状态,其中包括其父项和拥有它们的文档。无论是
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 document 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对参数
cloneNode()和
importNode()指定是否需要深拷贝,这意味着复制节点和所有它的孩子。由于您有99%的时间想要复制整个子树,因此几乎总是希望这是事实。



