SAXDemo.java

Copyright 2001, Gerry de Koning

/*
 * Copyright 2001, Gerry de Koning
 * 
 * This program is for educational purposes only.
 * It is an example only, and not designed to be
 * fit for any other purpose.
 */
import org.apache.xerces.parsers.*;
import org.xml.sax.*;
import java.io.*;

public class SAXDemo implements ContentHandler {
    private static Reader xmlFile;
    private static XMLReader reader;
    private Locator locator;

    public static void main (String[] args) throws Exception {
		switch (args.length) {
		case 1:
		    xmlFile = new FileReader(args[0]);
	    	reader = new SAXParser();
		    reader.setContentHandler(new SAXDemo());
		    reader.parse(new InputSource(xmlFile));
		    break;
		default:
	    	System.err.println("Usage:  java SAXDemo xmlFile");
	    	System.exit(1);
	    	break;
		}
    }

    public void setDocumentLocator(Locator locator) {
    	System.out.println("We have a locator!");
    	this.locator = locator;
    }

    public void startDocument() {
    	System.out.println("Start of document");
    }

    public void endDocument() {
    	System.out.println("End of Document");
    }

	public void startElement(String namespace, 
					String name, String qName, Attributes atts) {
		System.out.println("\nAt line " 
			+ locator.getLineNumber() + " column "
			+ locator.getColumnNumber() + ":");
		System.out.println("Start Element: " + qName);
		for (int i=0; i < atts.getLength(); i++) {
			System.out.println("     Attribute: "
				+ atts.getQName(i) + " ("
				+ atts.getValue(i) + ")");
		}
    }

    public void endElement(String namespace, 
    				String name, String qName) {
    	System.out.println("End of Element: " + qName);
    }

    public void characters(char[] ch, int start, int length) {
    	System.out.println("Characters: >>"
    		+ new String(ch, start, length) + "<<");
    }

    public void processingInstruction(String target, String data) {
    	System.out.println("Processing instruction: "
    		+ target + " (" + data +")");
    }

    public void startPrefixMapping(String prefix, String uri) {}
    public void endPrefixMapping(String prefix) {}
    public void ignorableWhitespace(
    						char[] ch, int start, int length) {}
    public void skippedEntity(String name) {}
}