Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
648 views
in Technique[技术] by (71.8m points)

api - How do I copy DOM nodes from one document to another in Java?

I'm having trouble with copying nodes from one document to another one. I've used both the adoptNode and importNode methods from Node but they don't work. I've also tried appendChild but that throws an exception. I'm using Xerces. Is this not implemented there? Is there another way to do this?

List<Node> nodesToCopy = ...;
Document newDoc = ...;
for(Node n : nodesToCopy) {
    // this doesn't work
    newDoc.adoptChild(n);
    // neither does this
    //newDoc.importNode(n, true);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is that Node's contain a lot of internal state about their context, which includes their parentage and the document by which they are owned. Neither adoptChild() nor importNode() place the new node anywhere in the destination document, which is why your code is failing.

Since you want to copy the node and not move it from one document to another there are three distinct steps you need to take...

  1. Create the copy
  2. Import the copied node into the destination document
  3. Place the copied into it's correct position in the new document
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);
}

The Java Document API allows you to combine the first two operations using 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);
}

The true parameter on cloneNode() and importNode() specifies whether you want a deep copy, meaning to copy the node and all it's children. Since 99% of the time you want to copy an entire subtree, you almost always want this to be true.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...