使用SAXParser脱机验证XML(gpx)架构

时间:2012-01-10 18:40:25

标签: java xsd validation offline gpx

我使用以下代码来针对指定的XML架构验证XML文档(.gpx)。我将架构存储在本地作为.xsd文件。问题是,此方法使用Internet连接来验证架构。有没有办法我可以不使用互联网连接? (鉴于我在本地存储XML模式这一事实。)

代码:

    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;
}

谢谢和问候,

斯托

3 个答案:

答案 0 :(得分:0)

使用“file://”网址引用您的本地架构。

答案 1 :(得分:0)

schemaUrl指定为"file://path/to/schema.xsd"

答案 2 :(得分:0)

Yoy可以通过你自己的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);
            }
} )
相关问题