import java.util.Stack;

import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class Handler extends DefaultHandler {
    StringBuilder text = new StringBuilder();
    String chapter;

    // SAX calls this method when it encounters an element
    @Override
    public void startElement(String namespaceURI,
                             String localName,
                             String qualifiedName,
                             Attributes att)
            throws SAXException {
        if ("chapter".equals(qualifiedName)) {
            chapter = att.getValue(0);
            System.out.print("\nChapter " + chapter + ": ");
        }
        else if ("author".equals(qualifiedName)) {
            System.out.print("  by ");
        }
    }

    // SAX calls this method to pass in character data
    @Override
    public void characters(char ch[], int start, int length)
            throws SAXException {
        text.append(new String(ch, start, length));
    }

    // SAX calls this method when it encounters an end tag
    @Override
    public void endElement(String namespaceURI,
                           String localName,
                           String qualifiedName)
            throws SAXException {
        String s = text.toString();
        if (s.length() > 0) {
            System.out.println(s);
            text = new StringBuilder();
        }
        if ("chapter".equals(qualifiedName)) {
            System.out.println("-- End of chapter " + chapter + " --");
        }
    }
}

