how to clone a DOM document?

A

Andy Fish

Hi,

I am trying to figure out how to make a complete copy of a DOM document. I
am using xerces but vanilla DOM would obviously be the best solution. The
nearest I have got is something like:

Document newDoc = new DocumentImpl();

newDoc.appendChild(newDoc.importNode(oldDoc.getDocumentElement(),true));

but I presume this won't do namespace declarations, processing instructions,
the <?xml> declaration at the front etc etc.

I would have thought this would be a FAQ but I can't find anything obvious
anywhere.

many thanks

Andy
 
R

Rolf Magnus

Andy said:
Hi,

I am trying to figure out how to make a complete copy of a DOM
document. I am using xerces but vanilla DOM would obviously be the
best solution. The nearest I have got is something like:

Document newDoc = new DocumentImpl();

newDoc.appendChild(newDoc.importNode(oldDoc.getDocumentElement(),true));

but I presume this won't do namespace declarations, processing
instructions, the <?xml> declaration at the front etc etc.

Try something like:

newDoc = oldDoc.cloneNode(true);
 
A

Andy Fish

Hey thanks Rolf, I must admit I'm kinda surprised that worked, but it
definitely worked for me.

Normally calling clone on a node returns somethng owned by the same document
as the original node, so I didn't think it would even be supported on a
document.

I notice that the javadoc for org.w3c.dom does not mention cloning a
document as a special case, but the w3c core specification says cloning a
document is implementation specific.

Andy
 

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,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top