Java XML Attribute Copy copyAttributes(Element elementFrom, Element elementTo)

Here you can find the source of copyAttributes(Element elementFrom, Element elementTo)

Description

Copies all attributes from one element to another in the official way.

License

Open Source License

Declaration

public static void copyAttributes(Element elementFrom, Element elementTo) 

Method Source Code


//package com.java2s;
/*/*from  w  w  w.  ja va  2s. co  m*/
 * Copyright (C) 2010  Just Objects B.V.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import org.w3c.dom.*;

public class Main {
    /**
     * Copies all attributes from one element to another in the official way.
     */
    public static void copyAttributes(Element elementFrom, Element elementTo) {
        NamedNodeMap nodeList = elementFrom.getAttributes();
        if (nodeList == null) {
            // No attributes to copy: just return
            return;
        }

        Attr attrFrom = null;
        Attr attrTo = null;

        // Needed as factory to create attrs
        Document documentTo = elementTo.getOwnerDocument();
        int len = nodeList.getLength();

        // Copy each attr by making/setting a new one and
        // adding to the target element.
        for (int i = 0; i < len; i++) {
            attrFrom = (Attr) nodeList.item(i);

            // Create an set value
            attrTo = documentTo.createAttribute(attrFrom.getName());
            attrTo.setValue(attrFrom.getValue());

            // Set in target element
            elementTo.setAttributeNode(attrTo);
        }
    }
}

Related

  1. copyAllAttributes(Element from, Element to)
  2. copyAllAttributes(Element source, Element dest, Set ignore)
  3. copyAttribute(Element source, String srcattr, Element dest, String destattr)
  4. copyAttribute(Element sourceElement, String sourceAttrName, Element visualElement, String visualAttrName)
  5. copyAttributeNodes(Element source, Element target)
  6. copyAttributes(Element from, Element to)
  7. copyAttributes(Element from, Element to, NodeFilter filter)
  8. copyAttributes(Element fromEl, Element toEl)
  9. copyAttributes(final Element destElement, final Element srcElement)