Validate XML(gpx) schema with SAXParser offline

1.2k Views Asked by At

I am using the following code to validate an XML document (.gpx) against a specified XML schema. I am storing the schema locally as a .xsd file. The problem is that, this method uses internet connection to validate the schema. Is there a way I can do it without using internet connection ? (given the fact that I am storing the XML schema locally).

The code:

    public static boolean validate(String XmlDocumentUrl, String SchemaUrl) {
    SAXParser parser = new SAXParser();
    try {
        parser.setFeature("http://xml.org/sax/features/namespaces", true);

        parser.setFeature("http://xml.org/sax/features/validation", true);
        parser.setFeature(
                "http://apache.org/xml/features/validation/schema", true);
        parser.setFeature(
                "http://apache.org/xml/features/validation/schema-full-checking",
                false);
        parser.setProperty(
                "http://apache.org/xml/properties/schema/external-schemaLocation",
                SchemaUrl);
        Validator handler = new Validator();

        parser.setErrorHandler(handler);
        parser.parse(XmlDocumentUrl);
        if (handler.validationError == true){
            System.out.println("XML Document has Error:"

                    + handler.validationError + ""
                    + handler.saxParseException.getMessage());
        return false;
        }
        else{
            System.out.println("XML Document is valid");
        return true;
        }
    } catch (java.io.IOException ioe) {
        System.out.println("IOException" + ioe.getMessage());
    } catch (SAXException e) {
        System.out.println("SAXException" + e.getMessage());
    }
    return false;
}

Thanks and regards,

Petar

3

There are 3 best solutions below

0
On

Use a "file://" url to reference your local schema.

2
On

Specify schemaUrl as "file://path/to/schema.xsd".

0
On

Yoy can pass you own implementation of DefaultHandler:

...SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(InputSource, new Defaulthandler() {
@Override
            public InputSource resolveEntity(String publicId, String systemId)
                    throws IOException, SAXException {
                InputStream is = ClassLoader.getSystemResourceAsStream("path_to_you_local_dtd_doc");
                return is != null ? new InputSource(is) :
                    super.resolveEntity(publicId, systemId);
            }
} )