Java examples for XML:XML Attribute
Copies all attributes from one XML element to another in the official way.
/*/* w w w . j a va 2s . com*/ * 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/>. */ //package com.java2s; 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); } } }