0

我正在使用以下代码针对指定的 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;
}

谢谢并恭祝安康,

佩塔尔

4

3 回答 3

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);
            }
} )
于 2014-03-03T15:10:54.580 回答
0

使用“file://”url 来引用您的本地架构。

于 2012-01-10T18:52:21.327 回答
0

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

于 2012-01-10T18:54:39.353 回答