| CIT 597 First SAX Example Fall 2002, David Matuszek |
Here is a trivial example of using SAX, taken from CodeNotes® for XML,
by Gregory Brill. This code is available as a zip
file containing a BlueJ package. Note that you must either run the program
from the command line, or move the hello.xml file into whatever
directory your IDE uses as its default directory.
Sample.java |
import org.xml.sax.*; import org.xml.sax.helpers.*; import javax.xml.parsers.*; /** * This is from CodeNotes for XML, by Gregory Brill, page 159. * I have made a few changes. */ public class Sample { public static void main(String args[]) throws Exception { // create a parser SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); SAXParser saxParser = spf.newSAXParser(); XMLReader parser = saxParser.getXMLReader(); // create a handler Handler handler = new Handler(); // assign the handler to the parser parser.setContentHandler(handler); // parse the document parser.parse("hello.xml"); } } |
Handler.java |
import org.xml.sax.*; import org.xml.sax.helpers.*; /** * This is from CodeNotes for XML, by Gregory Brill, page 158. * I have made some minor cosmetic changes. */ public class Handler extends DefaultHandler { // SAX calls this method when it encounters an element public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes att) throws SAXException { System.out.println("startElement: " + qualifiedName); } // SAX calls this method to pass in character data public void characters(char ch[], int start, int length) throws SAXException { System.out.println("characters " + start + " to " + (start + length - 1) + ": " + new String(ch, start, length)); } // SAX call this method when it encounters an end tag public void endElement(String namespaceURI, String localName, String qualifiedName) throws SAXException { System.out.println("Element: /" + qualifiedName); } } |
hello.xml |
<?xml version="1.0"?>
<display>
Hello World!
</display>
|
Example output |
startElement: display characters 32 to 31: characters 0 to 0: characters 34 to 49: Hello World! characters 0 to 0: endElement: /display |