View RSS Feed

Java XML

Java SAX Parser

Rate this Entry
by , 04-27-2012 at 06:15 PM (1178 Views)
SAX is an abbreviation and means "Simple API for XML". A Java SAX XML parser is a stream oriented XML parser. It works by iterating over the XML and call certain methods on a "listener" object when it meets certain structural elements of the XML. For instance, it will call the listener object for the following "events":
- startDocument
- startElement
- characters
- comments
- processing instructions
- endElement
- endDocument
This list is probably not complete, but it is long enough to give you an idea of how it works. Let's move on to see how you create and use a Java SAX Parser.
Java Code:
SAXParserFactory factory = SAXParserFactory.newInstance();
try {

    InputStream    xmlInput  = new FileInputStream("theFile.xml");
    SAXParser      saxParser = factory.newSAXParser();

    DefaultHandler handler   = new SaxHandler();
    saxParser.parse(xmlInput, handler);

} catch (Throwable err) {
    err.printStackTrace ();
When you call the SAXParser.parse() method the SAX parser starts the XML processing. ThexmlInput InputStream passed as parameter to the parse() method is where the XML is read from.
Notice the SaxHandler instance being created, and passed as parameter to the parse() method. The SaxHandler class is a subclass of the class org.xml.sax.helpers.DefaultHandler. TheDefaultHandler class comes with the JDK.
While processing the XML the SAXParser calls methods in the DefaultHandler subclass (here, the SaxHandler) instance corresponding to what the parser finds in the XML file. To react to those method calls you override the corresponding methods in the DefaultHandler subclass.

Submit "Java SAX Parser" to Facebook Submit "Java SAX Parser" to Digg Submit "Java SAX Parser" to Submit "Java SAX Parser" to StumbleUpon Submit "Java SAX Parser" to Google