Here you can find the source of cloneDOM(Node node, Document document)
public static Node cloneDOM(Node node, Document document)
//package com.java2s; // for Our Notice and the LICENSE file for the GNU Lesser General Public import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; public class Main { /**/*from w w w . j a v a2 s .co m*/ * Recursively copy the DOM tree using the specified document as the * root document factory. Only element and text nodes are supported. */ public static Node cloneDOM(Node node, Document document) { Node clone = null; if (node != null) { switch (node.getNodeType()) { /* * Clone the attributes and children of an element node. */ case Node.ELEMENT_NODE: clone = document.createElement(node.getNodeName()); NamedNodeMap attrs = node.getAttributes(); int nattrs = (attrs == null ? 0 : attrs.getLength()); for (int a = 0; a < nattrs; a++) { Attr attr = (Attr) attrs.item(a); ((Element) clone).setAttribute(attr.getName(), attr.getValue()); } Node c = node.getFirstChild(); while (c != null) { clone.appendChild(cloneDOM(c, document)); c = c.getNextSibling(); } break; /* * Clone the text data for CDATA and text nodes. */ case Node.CDATA_SECTION_NODE: case Node.TEXT_NODE: clone = document.createTextNode(node.getNodeValue()); break; /* * Ignore all other node types. */ default: break; } } return clone; } }