Java HTML / XML How to - Copy the attributes on one element to the other








Question

We would like to know how to copy the attributes on one element to the other.

Answer

  // w w  w.j a va 2 s.c o m

import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;

public class Main {

  public static void copyAttributes(Element from, Element to) {
      NamedNodeMap attributes = from.getAttributes();
      for (int i = 0; i < attributes.getLength(); i++) {
          Attr node = (Attr) attributes.item(i);
          to.setAttributeNS(node.getNamespaceURI(), node.getName(), node.getValue());
      }
  }
}