Java XML Node Clone cloneNode(Node node)

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

Description

Currently only use by GIFStreamMetadata and GIFImageMetadata

License

Apache License

Parameter

Parameter Description
node a parameter

Declaration

public static Node cloneNode(Node node) 

Method Source Code


//package com.java2s;
/*//from   w  w w .  j  ava2  s .com
 * Copyright 1999-2101 Alibaba Group.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import javax.imageio.metadata.IIOMetadataNode;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    /**
     * Currently only use by GIFStreamMetadata and GIFImageMetadata
     * @param node
     * @return
     */
    public static Node cloneNode(Node node) {
        if (node == null) {
            return null;
        }

        IIOMetadataNode newNode = new IIOMetadataNode(node.getNodeName());
        //clone user object
        if (node instanceof IIOMetadataNode) {
            IIOMetadataNode iioNode = (IIOMetadataNode) node;
            Object obj = iioNode.getUserObject();
            if (obj instanceof byte[]) {
                byte[] copyBytes = ((byte[]) obj).clone();
                newNode.setUserObject(copyBytes);
            }
        }

        //clone attributes
        NamedNodeMap attrs = node.getAttributes();
        for (int i = 0; i < attrs.getLength(); i++) {
            Node attr = attrs.item(i);
            newNode.setAttribute(attr.getNodeName(), attr.getNodeValue());
        }

        //clone children
        NodeList children = node.getChildNodes();
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            newNode.appendChild(cloneNode(child));
        }

        return newNode;
    }
}

Related

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