SAX2 Event Reporter
import org.xml.sax.*;
import org.apache.xerces.parsers.*;
import java.io.*;
public class SAX2EventReporter implements ContentHandler {
public void setDocumentLocator(Locator locator) {}
// Methods simply duplicated from DocumentHandler in SAX1
public void startDocument() throws SAXException {
System.out.println("Document started");
}
public void endDocument() throws SAXException {
System.out.println("Document ended");
}
public void characters(char[] text, int start, int length)
throws SAXException {
System.out.println("Got some characters");
}
public void ignorableWhitespace(char[] text, int start, int length)
throws SAXException {
System.out.println("Got some ignorable white space");
}
public void processingInstruction(String target, String data)
throws SAXException {
System.out.println("Got a processing instruction");
}
// Changed methods for SAX2
public void startElement(String namespaceURI, String localName,
String rawName, Attributes atts) throws SAXException {
System.out.println("Element " + rawName + " started");
}
public void endElement(String namespaceURI, String localName,
String rawName) throws SAXException {
System.out.println("Element " + rawName + " ended");
}
// new methods for SAX2
public void startPrefixMapping(String prefix, String uri)
throws SAXException {
System.out.println("Started mapping prefix " + prefix + " to URI " + uri);
}
public void endPrefixMapping(String prefix) throws SAXException {
System.out.println("Stopped mapping prefix " + prefix);
}
public void skippedEntity(String name) throws SAXException {
System.out.println("Skipped entity " + name);
}
// Could easily have put main() method in a separate class
public static void main(String[] args) {
XMLReader parser = new SAXParser();
if (args.length == 0) {
System.out.println("Usage: java SAX2EventReporter URL1 URL2...");
}
// Install the Content Handler
parser.setContentHandler(new SAX2EventReporter());
// start parsing...
for (int i = 0; i < args.length; i++) {
// command line should offer URIs or file names
try {
parser.parse(args[i]);
}
catch (SAXParseException e) { // well-formedness error
System.out.println(args[i] + " is not well formed.");
System.out.println(e.getMessage()
+ " at line " + e.getLineNumber()
+ ", column " + e.getColumnNumber());
}
catch (SAXException e) { // some other kind of error
System.out.println(e.getMessage());
}
catch (IOException e) {
System.out.println("Could not report on " + args[i]
+ " because of the IOException " + e);
}
}
}
}