简体   繁体   中英

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>

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)));

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM