Code example for SAXParser: Parsing XML documents

Methods: getXMLReader, parse, setProperty

0
SAXParser parser = newSAXParser(schema, schemaStream, loadExternalDtds);
 
            if (lHandler != null) {
                try { 
                    parser.setProperty("http://xml.org/sax/properties/lexical-handler", lHandler);
                } catch (SAXException ex) {
                    Message.warn("problem while setting the lexical handler property on SAXParser (" 
                            + ex.getClass().getName() + ": " + ex.getMessage() + ")");
                    // continue without the lexical handler 
                } 
            } 
 
            parser.parse(xmlStream, handler);
        } finally { 
            if (schemaStream != null) {
                try { 
                    schemaStream.close();
                } catch (IOException ex) {
                    // ignored 
                } 
            } 
        } 
    } 
 
    private static SAXParser newSAXParser(URL schema, InputStream schemaStream,
            boolean loadExternalDtds) throws ParserConfigurationException, SAXException {
        SAXParserFactory parserFactory = SAXParserFactory.newInstance();
        parserFactory.setNamespaceAware(true);
        parserFactory.setValidating(canUseSchemaValidation && (schema != null));
        if (!loadExternalDtds && canDisableExternalDtds(parserFactory)) {
            parserFactory.setFeature(XERCES_LOAD_EXTERNAL_DTD, false);
        } 
        SAXParser parser = parserFactory.newSAXParser();
 
        if (canUseSchemaValidation && (schema != null)) {
            try { 
                parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
                parser.setProperty(JAXP_SCHEMA_SOURCE, schemaStream);
            } catch (SAXNotRecognizedException ex) {
                Message.warn("problem while setting JAXP validating property on SAXParser... " 
                        + "XML validation will not be done (" + ex.getClass().getName() + ": "
                        + ex.getMessage() + ")");
                canUseSchemaValidation = false;
                parserFactory.setValidating(false);
                parser = parserFactory.newSAXParser();
            } 
        } 
 
        parser.getXMLReader().setFeature(XML_NAMESPACE_PREFIXES, true);
        return parser;
    } 
 
    private static boolean canDisableExternalDtds(SAXParserFactory parserFactory) {
        if (canDisableExternalDtds == null) {