// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package xmlproc;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

public class ParseSAX {
    private final static String XML_FILE = "/work/employees.xml";
    public static void main(String[] args) throws Exception {
        // process file with MySaxParser as event handler
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        xr.setContentHandler(new MySaxParser());
        xr.parse(XML_FILE);
    }
}

class MySaxParser extends DefaultHandler {
    private StringBuilder sb = new StringBuilder();
    // accumulate text (note: can be called multiple times for a text node)
    public void characters(char buf[], int offset, int len) throws SAXException {
        sb.append(new String(buf, offset, len));
    }
    // process start element, if 'employee' find attribute no
    public void startElement(String namespaceURI, String localName, String rawName, Attributes atts) throws SAXException {
        // if employee element find no and print
        if (rawName.equals("employee")) {
            String no = atts.getValue("no");
            System.out.println("no=" + no);
        }
        // if sub elements name or role start accumulating
        if (rawName.equals("name") || rawName.equals("role")) {
            sb = new StringBuilder();   
        }
    }
    // process end element, find elements name and role
    public void endElement(String namespaceURI, String localName, String rawName) throws SAXException {
        // if sub elements name or role stop accumulating and print
        if (rawName.equals("name")) {
            String name = sb.toString();
            System.out.println("name=" + name);
        }
        if (rawName.equals("role")) {
            String role = sb.toString();
            System.out.println("role=" + role);
        }
    }
}
