P1.java

import java.io.*;
import org.xml.sax.*;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.ParserAdapter;
import org.xml.sax.helpers.XMLReaderFactory;
import javax.xml.parsers.*;

/**
Simple demonstration of SAX.
Reads XML version of "Midsummer Night's Dream", prints all Act and 
Scene titles and stage directions, with indentation indicating the
nesting of the XML document.
*/
public class P1 extends DefaultHandler
{
    public static void main(String[] argv)
    {
        // Must choose a parser that's on the CLASSPATH.
        String saxClass = "org.apache.xerces.parsers.SAXParser";

        try {
            XMLReader p = XMLReaderFactory.createXMLReader(saxClass);
            DefaultHandler h = new P1();
            p.setContentHandler(h);
            FileInputStream f = 
                new FileInputStream(
                    new File("dream.xml"));
            p.parse(new InputSource(f));
            }
        catch (SAXException eSax) {
            eSax.printStackTrace();
            }
        catch (Exception e) {
            e.printStackTrace();
            }
    }

    public P1()
    {
        capture = true;
        level = 0;
        accum = new StringBuffer("");
    }

    public void startElement(
            String namespaceURI,
            String sName,
            String qName,
            Attributes attribs) 
        throws SAXException
    {
        level += 1;
        if (qName.equals("STAGEDIR") || qName.equals("TITLE"))
            capture = true;
    }

    public void endElement(
            String namespaceURI,
            String sName,
            String qName)
        throws SAXException
    {
        level -= 1;
        if (qName.equals("STAGEDIR") ||  qName.equals("TITLE")) {
            capture = false;
            if (qName.equals("TITLE"))
                System.out.println();
            for (int i=0; i<level-1; i++) // level=1 == no indent
                System.out.print("   ");
            String data = accum.toString();
            data = data.trim().replaceAll("\\s+"," " );
            System.out.println(data);
            accum = new StringBuffer("");
            }
    }

    public void characters(char buf[],int offset,int len)
        throws SAXException
    {
        if (capture) {
            String s = new String(buf,offset,len);
            accum.append(s);
            }
    }

    public void error(SAXParseException e)
        throws SAXParseException
    {
        throw e;
    }

    private boolean capture;
    private int level;
    private StringBuffer accum;
}