[英]Copying an XML node from a document to another document using Java DOM Parser
I have been implementing a simple algorithm that parses an XML file and resort its nodes based on an attribute value in node . 我一直在实现一种简单的算法,该算法可以解析XML文件并根据node中的属性值重新排序其节点。 I retrieve all nodes and insert the whole node to a sorted ArrayList.
我检索所有节点,并将整个节点插入经过排序的ArrayList中。 Then I created a new XML document and created new and tags but when I try to copy sorted Node and append it to , an exception stating that is still used in another document.
然后,我创建了一个新的XML文档,并创建了new和标签,但是当我尝试复制已排序的Node并将其附加到时,出现了一个异常,指出仍在另一个文档中使用。 I am using
我在用
Node sortedCnode= cNode.cloneNode(false); //tried true as well
b.appendChild(sortedCnode);
I think my code is trying to append the whole true. 我认为我的代码试图将整个事实都追加。 But, I don't know the proper way to do it
但是,我不知道正确的方法
The XML looks like below XML如下所示
<A>
<B>
<C>
<D>
</D>
<E>
</E>
</C>
</B>
</A>
I figured it out 我想到了
to copy a node from source DOM to target DOM below should be used 将节点从源DOM复制到目标DOM的方法如下
targetBNode.appendChild(targetDOC.adoptNode(sourceCnode.cloneNode(true)));
A more complete answer is available here from Jherico: How do I copy DOM nodes from one document to another in Java . 可以从Jherico获得更完整的答案: 如何在Java中将DOM节点从一个文档复制到另一个文档 。
To summarize, you need to: 总而言之,您需要:
Jherico provides two methods, one using cloneNode() and adoptNode() which is the same as the accepted answer. Jherico提供了两种方法,一种使用cloneNode()和采用Node(),与接受的答案相同。 However, a shortcut method exists by using importNode() on Document which performs both of those operations for you.
但是,存在通过在Document上使用importNode()来执行两种操作的快捷方法。
targetBNode.appendChild(targetDOC.importNode(sourceCnode, true));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.