Java tutorial
//package com.java2s; import java.util.HashMap; import javax.activation.UnsupportedDataTypeException; import org.w3c.dom.Attr; import org.w3c.dom.CDATASection; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; public class Main { public static Document document; public static final Node copyElement(Node e) throws UnsupportedDataTypeException { Node result = null; switch (e.getNodeType()) { case Node.ELEMENT_NODE: result = document.createElement(e.getNodeName()); for (int i = 0; i < e.getAttributes().getLength(); i++) { Attr attr = document.createAttribute(e.getAttributes().item(i).getNodeName()); attr.setNodeValue(e.getAttributes().item(i).getNodeValue()); result.getAttributes().setNamedItem(attr); } break; case Node.CDATA_SECTION_NODE: result = document.createCDATASection(((CDATASection) e).getData()); break; case Node.TEXT_NODE: if (((Text) e).getTextContent().replaceAll("\t", "").trim() != "") result = document.createTextNode(((Text) e).getTextContent().replaceAll("\t", "").trim()); break; default: throw new UnsupportedDataTypeException(new StringBuilder(e.getNodeType()).toString()); } for (int i = 0; i < e.getChildNodes().getLength(); i++) result.appendChild(copyElement(e.getChildNodes().item(i))); return result; } public static Element createElement(String name) { return document.createElement(name); } public static Element createElement(String name, HashMap<String, Object> attributes) { Element e = document.createElement(name); for (String a : attributes.keySet()) if (attributes.get(a) instanceof String) e.setAttribute(a, (String) attributes.get(a)); return e; } public static CDATASection createCDATASection(String content) { return document.createCDATASection(content); } }