The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > org.w3c.dom  [30 examples] > Element Attributes  [5 examples]

e537. Removing All the Attributes in a DOM Element

The tricky part of removing all the attributes in an XML element is to realize that attributes with a default value cannot be removed. Therefore, the following code will never terminate if the element has an attribute with a default value:
    // Very bad code; may never terminate
    NamedNodeMap attrs = element.getAttributes();
    while (attrs.getLength() > 0) {
        attrs.removeNamedItem(attrs.item(0).getNodeName());
    }
This example removes all attributes by first making a copy of the attribute names and then using the list to remove the attributes:
    // Remove all the attributes of an element
    NamedNodeMap 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 Examples
e534. Getting and Setting an Attribute in a DOM Element
e535. Adding and Removing an Attribute in a DOM Element
e536. Listing All the Attributes of a DOM Element
e538. Determining If an Attribute Was Supplied in a DOM Element

See also: Adding and Removing Nodes    Elements    Getting Nodes    Text Nodes    XPath   


© 2002 Addison-Wesley.