tags:

views:

220

answers:

2

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);
}
+3  A: 

adoptChild does not create a duplicate, it just moves the node to another parent.

You probably want the cloneNode() method.

Uri
+1  A: 
for(Node n : nodesToCopy) {
    Node n2 = newDoc.adoptChild(n.cloneNode(true));
    newDoc.getDocumentElement().appendChild(n2);
}
Jherico