Tipworld -> XML
SAX Parsing with JAXP

Today's tip kicks off our discussion of parsing XML with Java using the JAXP parser from Sun. JAXP supports both DOM and SAX, and we'll begin with SAX. As you install the parser, be sure to add parser.jar and jaxp.jar to the CLASSPATH. Both of these files are located in the installation directory.


Now, to begin writing code, you must first import the packages that implement the SAX API:


import org.xml.sax.*;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;


You tell the parser what file to parse via a URI. For example, the following code defines a Java String that contains a URI to a file called myfile.xml in mydirectory on my C drive.

String uri = "file:c:\\mydirectory\\myfile.xml";

Now, here is an example of how the SAX code looks:


Parser parser=null; // document parser, from W3C API
// get a SAX Parser Factory
SAXParserFactory spf = SAXParserFactory.newInstance ();
// from the factory, create an instance of a SAXParser
SAXParser sp = spf.newSAXParser ();
// get the W3C compliant parser from the JAXP class
parser = sp.getParser ();
// give the parser a class to 'handle the document'
parser.setDocumentHandler (new MyDocumentHandler());
// parse it
parser.parse (uri);

AS you can see, it's a piece of cake. Next time, we'll delve a bit deeper and discuss MyDocumentHandler().