简体   繁体   English

如何将本地DTD文件的验证应用于java中的xml文件?

[英]How to apply validation of local DTD file to xml file in java?

I need to parse a bunch of incoming XML documents but it does not contain DTD declaration. 我需要解析一堆传入的XML文档,但它不包含DTD声明。 Currently I am parsing xml documents using SAX Parser but without DTD validation. 目前我正在使用SAX Parser解析xml文档但没有DTD验证。 Now I want to apply DTD validation. 现在我想应用DTD验证。 DTD is created by myself. DTD由我自己创建。 How can I validate an XML file using DTD created by myself (SAX parser) ? 如何使用自己创建的DTD(SAX解析器)验证XML文件? I found some tutorials using Transformer but all for DOM Parser. 我找到了一些使用Transformer的教程,但都是针对DOM Parser的。

How to parse XML file using SAX Parser and also applying DTD validation. 如何使用SAX Parser解析XML文件并应用DTD验证。 Any help.... 任何帮助......

Below is a sample that I believe could help to do what you want: 以下是我认为可以帮助您做到您想要的样本:

private void loadXML(Reader reader) throws ParserConfigurationException, SAXException {
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    parserFactory.setValidating(true);
    SAXParser parser = parserFactory.newSAXParser();
    parser.parse(new InputSource(reader), new MyHandler());
}

private static class MyHandler
        extends DefaultHandler {

    private static final String PREFS_DTD_URI = "http://www.example.com/dtd/document.dtd";

    public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
        if (systemId.equals(PREFS_DTD_URI)) {
            InputSource is = new InputSource(new StringReader(PREFS_DTD));  // PREFS_DTD is a string containing actual DTD, any other Reader could be here
            is.setSystemId(PREFS_DTD_URI);
            return is;
        }
        // else use the default behaviour
        return null;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM