问题描述
我在与从一个文档复制节点到另一个麻烦。我用两个从节点的adoptNode和importNode方法,但他们不工作。我也试着使用appendChild而是抛出异常。我使用的Xerces。这难道不是实现呢?是否有另一种方式来做到这一点?
列表<节点> nodesToCopy = ...;
文件newDoc = ...;
对于(节点N:nodesToCopy){
//这不起作用
newDoc.adoptChild(N);
//没有做到这一点
//newDoc.importNode(n,真正的);
}
问题是该节点的包含关于他们的背景,包括他们的出身和他们所拥有的文件很多内部状态。无论是 adoptChild()
也不 importNode()
将目标文档中的任意位置的新节点,这就是为什么你的code失败。
既然你要复制的节点,不是从一个文档移动到另一个有三个不同的步骤,你需要采取...
- 创建副本
- 导入拷贝节点到目标文档
- 将被复制到它在新的文件 正确的位置
对于(节点N:nodesToCopy){
//创建一个重复的节点
节点newNode = n.cloneNode(真);
//新节点的所有权转移到目标文档
newDoc.adoptNode(newNode);
//使新节点的实际项目的目标文档中
。newDoc.getDocumentElement()的appendChild(newNode);
}
在Java API文档可以让你的前两个操作结合使用 importNode()
。
对于(节点N:nodesToCopy){
//创建一个重复的节点,并转移所有权
//新节点到目标文档
节点newNode = newDoc.importNode(N,真正的);
//使新节点的实际项目的目标文档中
。newDoc.getDocumentElement()的appendChild(newNode);
}
在 cloneNode()
和 importNode()$ c中的
真正
参数$ C>指定是否要深拷贝,这意味着复制节点和所有它的孩子。既然你要复制的整个子树99%的时间,你几乎总是希望这是真的。
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);
}
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...
- Create the copy
- Import the copied node into the destination document
- Place the copied into it's correct position in the new document
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); }
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); }
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.
这篇关于我如何从一个文档复制DOM节点到另一个在Java中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!