Java XML Document Clone copyDocument(Document source)

Here you can find the source of copyDocument(Document source)

Description

Clone a Document object.

License

Open Source License

Parameter

Parameter Description
source The Document object to be cloned.

Exception

Parameter Description
ParserConfigurationException an exception

Return

the clone of the Document object

Declaration

public static Document copyDocument(Document source) throws ParserConfigurationException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;

import org.w3c.dom.Node;

public class Main {
    /**//from   w  w  w.  j a  va 2s.c o m
     * Clone a Document object.
     *
     * @param source
     *              The Document object to be cloned.
     *
      * @return the clone of the Document object
      *
     * @throws ParserConfigurationException 
     */
    public static Document copyDocument(Document source) throws ParserConfigurationException {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();

        Node originalRoot = source.getDocumentElement();

        Document copiedDocument = db.newDocument();
        Node copiedRoot = copiedDocument.importNode(originalRoot, true);
        copiedDocument.appendChild(copiedRoot);

        return copiedDocument;
    }
}

Related

  1. copyChildren(Element from, Element to, Document doc)
  2. copyChildren(final Document newDoc, final Node node, final Node newNode)
  3. copyDocument(Document document)
  4. copyDocument(Document from, Document to)
  5. copyDocument(Document oldDocument, Document newDocument)
  6. copyDocument(Element from, Element to, String newNamespace)
  7. copyDocumentNode(Node source, Document target)
  8. copyDomDocument(Document originalDomDoc)
  9. copyElement(Element orig, Document newOwner, Set blankTextNodes)