Java tutorial
//package com.java2s; import org.w3c.dom.Attr; import org.w3c.dom.CharacterData; 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 { /** * Convenience method to copy the contents of the old {@link Node} into the * new one. * * @param newDoc * @param newNode * @param oldParent */ public static void copyContents(Document newDoc, Node newNode, Node oldNode) { // FIXME we should be able to achieve this with much less code (e.g. // the code commented out) but for some reason there are // incompatibility issues being spat out by the tests. // final NodeList childNodes = oldNode.getChildNodes(); // for (int i = 0; i < childNodes.getLength(); i++) { // final Node child = newDoc.importNode(childNodes.item(i), true); // newNode.appendChild(child); // } final NodeList childs = oldNode.getChildNodes(); for (int i = 0; i < childs.getLength(); i++) { final Node child = childs.item(i); Element newElem = null; switch (child.getNodeType()) { case Node.ELEMENT_NODE: //Get all the attributes of an element in a map final NamedNodeMap attrs = child.getAttributes(); // Process each attribute newElem = newDoc.createElement(child.getNodeName()); for (int j = 0; j < attrs.getLength(); j++) { final Attr attr = (Attr) attrs.item(j); // add attribute name and value to the new element newElem.setAttribute(attr.getNodeName(), attr.getNodeValue()); } newNode.appendChild(newElem); break; case Node.TEXT_NODE: newNode.appendChild(newDoc.createTextNode(getString(child))); } copyContents(newDoc, newElem, child); } } @Deprecated private static String getString(Node child) { String s = ""; if (child instanceof CharacterData) { CharacterData cd = (CharacterData) child; s = cd.getData(); } while (s.startsWith("\n")) { s = s.substring(1); } return s; } }