Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 . 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>
like image 797
mowienay Avatar asked Oct 30 '25 14:10

mowienay


2 Answers

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)));
like image 143
mowienay Avatar answered Nov 01 '25 03:11

mowienay


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:

  1. Copy the node
  2. Import the copy into the destination document
  3. Position the copy in the new document

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));
like image 28
AngryMonkey Avatar answered Nov 01 '25 04:11

AngryMonkey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!