Reputation: 1354
I have been implementing a simple algorithm that parses an XML file and resort its nodes based on an attribute value in node . I retrieve all nodes and insert the whole node to a sorted 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. 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
<A>
<B>
<C>
<D>
</D>
<E>
</E>
</C>
</B>
</A>
Upvotes: 4
Views: 7975
Reputation: 144
A more complete answer is available here from Jherico: How do I copy DOM nodes from one document to another in Java.
To summarize, you need to:
Jherico provides two methods, one using cloneNode() and adoptNode() which is the same as the accepted answer. However, a shortcut method exists by using importNode() on Document which performs both of those operations for you.
targetBNode.appendChild(targetDOC.importNode(sourceCnode, true));
Upvotes: 2
Reputation: 1354
I figured it out
to copy a node from source DOM to target DOM below should be used
targetBNode.appendChild(targetDOC.adoptNode(sourceCnode.cloneNode(true)));
Upvotes: 7