Java tutorial
//package com.java2s; // are made available under the terms of the Eclipse Public License v1.0 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; import org.w3c.dom.NodeList; public class Main { /** * Clones the given DOM node into the given DOM document. * * @param node * The DOM node to clone. * @param doc * The target DOM document. * @return The cloned node in the target DOM document. */ public static Node cloneNode(Node node, Document doc) { Node clone = null; switch (node.getNodeType()) { case Node.ELEMENT_NODE: clone = doc.createElement(node.getNodeName()); NamedNodeMap attrs = node.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Node attrNode = attrs.item(i); Attr attrClone = doc.createAttribute(attrNode.getNodeName()); attrClone.setNodeValue(attrNode.getNodeValue()); ((Element) clone).setAttributeNode(attrClone); } // Iterate through each child nodes. NodeList childNodes = node.getChildNodes(); if (childNodes != null) { for (int i = 0; i < childNodes.getLength(); i++) { Node childNode = childNodes.item(i); if (childNode == null) { continue; } Node childClone = cloneNode(childNode, doc); if (childClone == null) { continue; } clone.appendChild(childClone); } } break; case Node.TEXT_NODE: case Node.CDATA_SECTION_NODE: clone = doc.createTextNode(node.getNodeName()); clone.setNodeValue(node.getNodeValue()); break; } return clone; } }