Here you can find the source of cloneDocument(final Document doc)
Parameter | Description |
---|---|
doc | The document to be cloned. |
Parameter | Description |
---|---|
TransformerException | Thrown if the document can't be |
public static Document cloneDocument(final Document doc) throws TransformerException
//package com.java2s; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import org.w3c.dom.Document; import org.w3c.dom.Node; public class Main { /**/* w w w .j a v a 2 s . c o m*/ * Clones a document object. * * @param doc The document to be cloned. * @return The new document object that contains the same data as the original document. * @throws TransformerException Thrown if the document can't be */ public static Document cloneDocument(final Document doc) throws TransformerException { final Node rootNode = doc.getDocumentElement(); // Copy the doctype and xml version type data final TransformerFactory tfactory = TransformerFactory.newInstance(); final Transformer tx = tfactory.newTransformer(); final DOMSource source = new DOMSource(doc); final DOMResult result = new DOMResult(); tx.transform(source, result); // Copy the actual content into the new document final Document copy = (Document) result.getNode(); copy.removeChild(copy.getDocumentElement()); final Node copyRootNode = copy.importNode(rootNode, true); copy.appendChild(copyRootNode); return copy; } }