Java XML Document Clone cloneDOM(Node node, Document document)

Here you can find the source of cloneDOM(Node node, Document document)

Description

Recursively copy the DOM tree using the specified document as the root document factory.

License

Open Source License

Declaration

public static Node cloneDOM(Node node, Document document) 

Method Source Code

//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;
    }
}

Related

  1. cloneAndAppend(Document document, Node node)
  2. cloneDocument(Document document)
  3. cloneDocument(final Document doc)
  4. cloneDocument(final Document doc)
  5. cloneDOM(final Document src)
  6. cloneNode(Document d, Node n)
  7. cloneNode(Document document, Node node, boolean deep)
  8. copy(Document from, Document to)
  9. copyChildren(Document new_doc, Node node, Node new_node)