Creating SAX Parsers

The code snippet on the right displays a SAX parser. The SAX parser is a JavaTM console program that takes a command-line argument specifying the name of the XML document to be parsed. The parser reads an input XML document to count the total number of elements in the document.

Similar to DOM, creating a SAX parser primarily involves defining the SAX API package, creating a parser object, and parsing the XML document.

  • Defining the SAX API
    To write a program that uses SAX parsing, you must first include the required packages in your source code. For example:

     import java.io.*;
     import java.lang.*;
     import org.xml.sax.*;
     import org.xml.sax.helpers.*;
     import javax.xml.parsers.*;


  • Creating a parser object
    The parser object represents the SAX parser and is used to parse an XML document. The following code creates the saxParser object that represents the SAX parser:

     SAXParserFactory factory = SAXParserFactory.newInstance();  SAXParser saxParser = factory.newSAXParser();

  • 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.