Removing All the Attributes in a DOM Element - Java XML

Java examples for XML:XML Attribute

Description

Removing All the Attributes in a DOM Element

Demo Code

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

public class Main {
  public static void main(String[] argv) {
    // Very bad code; may never terminate
    Element element = null;//from w  ww.  j a  v  a2  s  .  c  om
    NamedNodeMap attrs = element.getAttributes();
    while (attrs.getLength() > 0) {
      attrs.removeNamedItem(attrs.item(0).getNodeName());
    }
    // Remove all the attributes of an element
    attrs = element.getAttributes();
    String[] names = new String[attrs.getLength()];
    for (int i = 0; i < names.length; i++) {
      names[i] = attrs.item(i).getNodeName();
    }
    for (int i = 0; i < names.length; i++) {
      attrs.removeNamedItem(names[i]);
    }
  }
}

Related Tutorials