Cloning dom.Document object Cloning dom.Document object xml xml

Cloning dom.Document object


You could use importNode API on org.w3c.dom.Document:

Node copy = document.importNode(node, true);

Full Example

import java.io.File;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.Node;public class Demo {    public static void main(String[] args) throws Exception {        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();        DocumentBuilder db = dbf.newDocumentBuilder();        Document originalDocument = db.parse(new File("input.xml"));        Node originalRoot = originalDocument.getDocumentElement();        Document copiedDocument = db.newDocument();        Node copiedRoot = copiedDocument.importNode(originalRoot, true);        copiedDocument.appendChild(copiedRoot);    }}


TransformerFactory tfactory = TransformerFactory.newInstance();Transformer tx   = tfactory.newTransformer();DOMSource source = new DOMSource(doc);DOMResult result = new DOMResult();tx.transform(source,result);return (Document)result.getNode();

This would be the Java 1.5 solution for making a copy of the DOM document. Take a look at Transformer Factory and Transformer


you could clone a tree or only the node with DOMs cloneNode(boolean isDeepCopy) API.

Document originalDoc = parseDoc();Document clonedDoc = originalDoc.cloneNode(true);

unfortunately, since cloneNode() on Document is (according to API) implementation specific, we have to go for a bullet-proof way, that is, create a new Document and import cloned node's from the original document:

...Document clonedDoc = documentFactory.newDocument();cloneDoc.appendChild(  cloneDoc.importNode(originalDoc.getDocumentElement(), true));

note that none of operations are thread-safe, so either use them only locally, or Thread-Local or synchronize them.