如何在 Java 中将 DOM 节点从一个文档复制到另一个文档? [英] How do I copy DOM nodes from one document to another in Java?

查看:57
本文介绍了如何在 Java 中将 DOM 节点从一个文档复制到另一个文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having trouble with copying nodes from one document to another one. I've used both the adoptNode and importNode methods from Node but they don't work. I've also tried appendChild but that throws an exception. I'm using Xerces. Is this not implemented there? Is there another way to do this?

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

推荐答案

问题是 Node 包含很多关于它们的上下文的内部状态,包括它们的出身和拥有它们的文档.adoptChild()importNode() 都不会将新节点放置在目标文档中的任何位置,这就是您的代码失败的原因.

The problem is that Node's contain a lot of internal state about their context, which includes their parentage and the document by which they are owned. Neither adoptChild() nor importNode() place the new node anywhere in the destination document, which is why your code is failing.

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

Since you want to copy the node and not move it from one document to another there are three distinct steps you need to take...

  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() 组合前两个操作.

The Java Document API allows you to combine the first two operations using 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% 的情况下都希望复制整个子树,因此您几乎总是希望这是真的.

The true parameter on cloneNode() and importNode() specifies whether you want a deep copy, meaning to copy the node and all it's children. Since 99% of the time you want to copy an entire subtree, you almost always want this to be true.

这篇关于如何在 Java 中将 DOM 节点从一个文档复制到另一个文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆