【问题标题】:How do I copy DOM nodes from one document to another in Java?如何在 Java 中将 DOM 节点从一个文档复制到另一个文档?
【发布时间】:2010-10-26 18:32:48
【问题描述】:

我在将节点从一个文档复制到另一个文档时遇到问题。我已经使用了 Node 中的 adaptNode 和 importNode 方法,但它们不起作用。我也试过 appendChild 但这会引发异常。我正在使用 Xerces。这不是在那里实施的吗?有没有其他方法可以做到这一点?

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

【问题讨论】:

    标签: java api dom copy


    【解决方案1】:

    问题在于 Node 包含很多关于其上下文的内部状态,其中包括其父辈和拥有它们的文档。 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% 的时间您想要复制整个子树,因此您几乎总是希望这是真的。

    【讨论】:

      【解决方案2】:

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

      您可能需要 cloneNode() 方法。

      【讨论】:

        猜你喜欢
        • 2014-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-22
        • 2012-10-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多