public Document cloneDocument ( DOMImplementation domImpl , Document document ) { Element root = document . getDocumentElement ( ) ; // New document Document result = domImpl . createDocument ( root . getNamespaceURI ( ) , root . getNodeName ( ) , null ) ; Element rroot = result . getDocumentElement ( ) ; // Cloning the document element is a bit tricky. // This is adopted from DomUtilities#deepCloneDocument boolean before = true ; for ( Node n = document . getFirstChild ( ) ; n != null ; n = n . getNextSibling ( ) ) { if ( n == root ) { before = false ; copyAttributes ( result , root , rroot ) ; for ( Node c = root . getFirstChild ( ) ; c != null ; c = c . getNextSibling ( ) ) { final Node cl = cloneNode ( result , c ) ; if ( cl != null ) { rroot . appendChild ( cl ) ; } } } else { if ( n . getNodeType ( ) != Node . DOCUMENT_TYPE_NODE ) { final Node cl = cloneNode ( result , n ) ; if ( cl != null ) { if ( before ) { result . insertBefore ( cl , rroot ) ; } else { result . appendChild ( cl ) ; } } } } } return result ; }
Deep - clone a document .