Creating SAX Parsers (continued)

Parsing the XML document and handling events
The parser object parses the XML document and generates events. These events are processed by specific elements. The following code parses an XML document, which is specified as a command-line argument. In addition, the code specifies the methods that can count the total number of elements in the XML document.

  saxParser.parse(new File(argv[0]), new   SAXCounter());
  }
  public void startDocument() {count =   0;}
  public void startElement(String uri,   String localName, String
  qName,Attributes attributes) {
  count++;
  public void endDocument() {
  System.out.println("Total number of   elements: " + count); }
  }

import java.io.*;
import java.lang.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import javax.xml.parsers.*;
public class SAXCounter extends DefaultHandler {
static private int count = 0;
public static void main(String argv[]) throws     Exception{
    if (argv.length != 1) {
    System.out.println("Usage: java SAX
    Counter xmlFile");
    System.exit(1);
    }
    SAXParserFactory factory =     SAXParserFactory.newInstance();
    SAXParser saxParser = factory
    .newSAXParser();

    saxParser.parse(new File(argv[0]), new     SAXCounter());
    }
    public void startDocument() {count = 0;}
    public void startElement(String uri,String     localName, String qName, Attributes     attributes) {
    count++;
    }
    public void endDocument() {
    System.out.println("Total number of
    elements: " + count);
    }

Click the Next button to continue.