Professional Documents
Culture Documents
Part I
Ethan Cerami
New York University
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import java.io.IOException;
/**
* Basic SAX Example.
* Illustrates basic implementation of the SAX Content Handler.
*/
public class SAXBasic implements ContentHandler {
**
* Prints Command Line Usage
*/
private static void printUsage() {
System.out.println ("usage: SAXBasic xml-file");
System.exit(0);
**
* Main Method
* Options for instantiating XMLReader Implementation:
* 1) XMLReader parser = XMLReaderFactory.createXMLReader();
* 2) XMLReader parser = XMLReaderFactory.createXMLReader
* ("org.apache.xerces.parsers.SAXParser");
* 3) XMLReader parser = new org.apache.xerces.parsers.SAXParser();
*/
10/17/08 Simple API for XML (SAX), Part I 16
public static void main(String[] args) {
if (args.length != 1) {
printUsage();
}
try {
SAXBasic saxHandler = new SAXBasic();
XMLReader parser = XMLReaderFactory.createXMLReader
("org.apache.xerces.parsers.SAXParser");
parser.setContentHandler(saxHandler);
parser.parse(args[0]);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Continued…
10/17/08 Simple API for XML (SAX), Part I 25
Content Handler API (cont)
ignorableWhitespace Receive notification of
ignorable whitespace in
element content.
setDocumentLocator Receive an object for
locating the origin of SAX
document events.
startDocument Receive notification of the
beginning of a document.
startElement Receive notification of the
beginning of an element.
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
import org.xml.sax.SAXException;
import org.xml.sax.Attributes;
import org.xml.sax.XMLReader;
import java.io.IOException;
/**
* Basic SAX Example.
* Illustrates extending of DefaultHandler
*/
public class SAXDefaultHandler extends DefaultHandler {
/**
* Main Method
*/
public static void main(String[] args) {
if (args.length != 1) {
printUsage();
}
try {
SAXDefaultHandler saxHandler = new SAXDefaultHandler();
XMLReader parser = XMLReaderFactory.createXMLReader
("org.apache.xerces.parsers.SAXParser");