Listing All the Attributes of a DOM Element : Attribute « XML « Java Tutorial






import java.io.File;

import javax.xml.parsers.DocumentBuilderFactory;

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

public class Main {
  public static void main(String[] argv) throws Exception{
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setExpandEntityReferences(false);
    Document doc = factory.newDocumentBuilder().parse(new File("filename"));
    Element element = doc.getElementById("key1");
    NamedNodeMap attrs = element.getAttributes();

    int numAttrs = attrs.getLength();
    for (int i = 0; i < numAttrs; i++) {
      Attr attr = (Attr) attrs.item(i);
      String attrName = attr.getNodeName();
      String attrValue = attr.getNodeValue();
    }
  }
}








33.22.Attribute
33.22.1.Adding and Removing an Attribute in a DOM Element
33.22.2.Listing All the Attributes of a DOM Element
33.22.3.Removing All the Attributes in a DOM Element
33.22.4.Remove all attributes by first making a copy of the attribute names and then using the list to remove the attributes:
33.22.5.Determining If an Attribute Was Supplied in a DOM Element
33.22.6.Accessing attributes of an element
33.22.7.Getting and Setting an Attribute in a DOM Element
33.22.8.Extracting attribute values from XML elements