XML Gurus: help with cloning a node without using clone!

F

fmarchioni

Dear all,
I have to copy one piece of XML from one part of the document to
another. Unfortunately I cannot simply do a copy and paste:

Node nodeLeaf = nodeChild.cloneNode(true);
nodeAncestor.appendChild(nodeLeaf);

because some fragments of the nodeLeaf mustn't be copied (depending on
the node value)

So I cannot make a deep clone of the leaf.
I have to make a clone of nodeLeaf by myself. (Copying its child with a
recursive function)

I have built a recursive function but I cannot understand why it
doesn't work correclty (text values are skipped and also some pieces of
the xml aren't copied correclty)

// Passing the full leaf and a leaf with only the first tag, under
which I clone manually the nodes.

Node copyNode = appendNodes(nodeLeaf, nodeLeaf.cloneNode(false));

private Node appendNodes(Node node, Node copyNode) {

NodeList kids = node.getChildNodes();
int length = kids.getLength();

if (kids != null) {
for (int ii = 0; ii < length; ii++) {
Node nodeKid = kids.item(ii);

copyNode.appendChild(nodeKid.cloneNode(false));

appendNodes(nodeKid,nodeKid);
}
}
return copyNode;
}

Anybody can give me a help ?
thanks a lot
Francesco
 
R

Roedy Green

Anybody can give me a help ?
Try dumping some debug output and watch your code work on a small
file. put in comments when you enter and leave the recursive method,
or keep a depth counter to add to you debug output.
 
N

Nils Bandener

if (kids != null) {
for (int ii = 0; ii < length; ii++) {
Node nodeKid = kids.item(ii);

copyNode.appendChild(nodeKid.cloneNode(false));

appendNodes(nodeKid,nodeKid);
^^^^^^^
Shouldn't the second nodeKid be actually the return value from the
previous nodeKid.cloneNode(false)?

Your version will append all descendants of the node to be cloned as
direct children to the cloned node.

Bye

Nils
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top