Java XML Document Clone cloneDocument(final Document doc)

Here you can find the source of cloneDocument(final Document doc)

Description

Clones a document object.

License

Open Source License

Parameter

Parameter Description
doc The document to be cloned.

Exception

Parameter Description
TransformerException Thrown if the document can't be

Return

The new document object that contains the same data as the original document.

Declaration

public static Document cloneDocument(final Document doc) throws TransformerException 

Method Source Code

//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;
    }
}

Related

  1. clone(Document doc)
  2. clone(Document inDoc)
  3. cloneAndAppend(Document document, Node node)
  4. cloneDocument(Document document)
  5. cloneDocument(final Document doc)
  6. cloneDOM(final Document src)
  7. cloneDOM(Node node, Document document)
  8. cloneNode(Document d, Node n)