如何在Java中将DOM节点从一个文档复制到另一个文档?

35

我在将节点从一个文档复制到另一个文档时遇到了问题。我尝试使用Node的adoptNode和importNode方法,但它们都不起作用。我还尝试过appendChild,但会抛出异常。我正在使用Xerces。这个方法在Xerces中没有实现吗?有其他方法可以做到这一点吗?

List<Node> nodesToCopy = ...;
Document newDoc = ...;
for(Node n : nodesToCopy) {
    // this doesn't work
    newDoc.adoptChild(n);
    // neither does this
    //newDoc.importNode(n, true);
}
2个回答

87

问题在于节点包含大量有关其上下文的内部状态,包括它们的父级和所属的文档。 adoptChild()importNode() 都不会将新节点放置在目标文档中的任何位置,这就是为什么您的代码失败的原因。

由于您想要复制节点而不是将其从一个文档移动到另一个文档,因此需要进行三个不同的步骤...

  1. 创建副本
  2. 将已复制的节点导入目标文档
  3. 将已复制的节点放置在新文档中的正确位置
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);
}

cloneNode()importNode() 上的 true 参数指定是否需要进行深度复制,即复制节点及其所有子节点。由于99%的情况下都需要复制整个子树,因此几乎总是需要将其设置为 true。


4

adoptChild方法并不会创建一个副本,它只是将节点移动到另一个父节点下。

您可能需要使用cloneNode()方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接