Java XML Node Clone cloneNode(Node node, Document doc)

Here you can find the source of cloneNode(Node node, Document doc)

Description

Clones the given DOM node into the given DOM document.

License

Open Source License

Parameter

Parameter Description
node The DOM node to clone.
doc The target DOM document.

Return

The cloned node in the target DOM document.

Declaration

public static Node cloneNode(Node node, Document doc) 

Method Source Code

//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 {
    /**/*from  w ww  .  j  av  a 2  s  .  co  m*/
     * 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;
    }
}

Related

  1. clone(final N node)
  2. cloneNode(Node node)
  3. cloneNode(Node node, Document target, boolean deep)
  4. copyGraphicFiles(String baseFilename, String currentDirectory, String fileSeparator, NodeIterator graphicsElements)
  5. copyInto(Node src, Node dest)
  6. copyNode(Node source)