Extracting attribute values from XML elements : Attribute « XML « Java Tutorial






import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class Main {
  public static void main(String[] argv) throws Exception {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();
    SaxHandler handler = new SaxHandler();
    parser.parse("sample.xml", handler);
  }

}

class SaxHandler extends DefaultHandler {
  public void startElement(String uri, String localName, String qName, Attributes attrs)
      throws SAXException {
    if (qName.equals("order")) {
      String date = attrs.getValue("date");
      String number = attrs.getValue("number");
      System.out.println("Order #" + number + " date is '" + date + "'");
    }
  }
}








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