我将节点从一个文档复制到另一个文档时遇到了问题.我已经使用了Node的adoptNode和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);
}
Run Code Online (Sandbox Code Playgroud)
Jhe*_*ico 71
问题是Node包含很多关于其上下文的内部状态,包括它们的父系和它们所拥有的文档.既不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%的时间你想复制整个子树,你几乎总是希望这是真的.