OptionalParser.java



import javax.xml.parsers.*;
import org.xml.sax.*;

/** SAX Parser */
public class OptionalParser
             implements org.apache.xerces.jaxp.JAXPConstants {

  /** Reader */
    private XMLReader reader = null;

  /** handlers */
    ContentHandler conHandler;
    ErrorHandler errHandler;

  /** option flags */
    boolean doValid;
    boolean isSchema;

  /** Constructor */
    public OptionalParser( ContentHandler conHandler, ErrorHandler errHandler,
                           boolean doValid, boolean isSchema ) {

        this.conHandler = conHandler;
        this.errHandler = errHandler;
        this.doValid = doValid;
        this.isSchema = isSchema;

        try {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            spf.setNamespaceAware( true );
            if( doValid )
                spf.setValidating( true );
            SAXParser parser = spf.newSAXParser();
            if( isSchema )
                parser.setProperty( JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA );
            reader = parser.getXMLReader();
            reader.setContentHandler( conHandler );
            reader.setErrorHandler( errHandler );
        }
        catch( Exception e ) {
            System.err.println( e.toString() );
        }
    }

  /** public parse method */
    public void parse( InputSource source ) {
        try {
            reader.parse( source );
        }
        catch( Exception e ) {
            System.err.println( e.toString() );
        }
    }

  /** main (for test) */
    public static void main( String[] argv ) {
        try {
            OptionalParser test
              = new OptionalParser( new MyContentHandler(),
                                    new MyErrorHandler(),
                                    true, true );
            InputSource source = new InputSource( argv[0] );
            test.parse( source );
        }
        catch( Exception e ) {
            System.err.println( e.toString() );
        }
    }
}