Java Tutorial - Java Scipt : SAX Parser Test

Java Tutorial - Java Scipt :

SAX Parser Test


This is a minimal example demonstrating the use of the standard SAX interfaces. The example relies on the default implementation that is shipped as part of JDK 1.4. SAX operates at a fairly low level and is generally used for parsing input from an input source. We’ll use it in a similar manner in this example to print out the names and attributes of elements as they are pushed to the program by SAX.

A survey of SAX usage shows that it is rarely output oriented. Higher-level XML tools, such as dom4j and JDOM, provide “pretty printers” for formatting XMLoutput in a way that makes it easier to read by human beings. This example program provides the beginnings of what could be a primitive output program based on SAX.

 Because XML is human-readable text, it is trivial to output a valid XML document through the traditional output methods such as println().

Note that we create a subclass of the DefaultHandler class to hook in the logic we want performed when a SAX event is encountered. MyDocHandler only handles two events: startElement and endElement. There’s not
much processing involved. The most complicated code loops through the element’s attributes and prints them out.
Here’s the source for jdk14_sax_test.java:

import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.*;
class MyDocHandler extends DefaultHandler {
public void startElement(
String sNamespace,
String sLocalName,
String sQualifiedName,
Attributes oAttributes )
throws SAXException
{
// --- Print out what the element we are passed in is. ---
System.out.println( sQualifiedName + “ started.” );
for( int idxAttribute = 0;
idxAttribute < oAttributes.getLength();
++idxAttribute )
{
System.out.println( “ (“ + oAttributes.getQName( idxAttribute ) +
“ = “ + oAttributes.getValue( idxAttribute ) +
“)” );
}
}
public void endElement(
String sNamespace,
String sLocalName,
String sQualifiedName )
{
System.out.println( sQualifiedName + “ ended.” );
}
}
public class jdk14_sax_test {
public static void main( String args[] )
{
// --- Parse order.xml. ---
DefaultHandler oHandler = new MyDocHandler();
SAXParserFactory oFactory = SAXParserFactory.newInstance();
try {
SAXParser oParser = oFactory.newSAXParser();
oParser.parse( “order.xml”, oHandler );
}
catch( Exception e ) {
e.printStackTrace();
}
}
}

To compile jdk14_sax_test.java, run the following command:

javac jdk14_sax_test.java

Running the example program is equally simple. Use:

java jdk14_sax_test