如何在LSParser中禁用DTD验证?

时间:2014-12-19 10:22:25

标签: java dom

我使用以下代码来解析XML文件并构造Document节点。

    String oldValue = System.getProperty(DOMImplementationRegistry.PROPERTY);
    System.setProperty(DOMImplementationRegistry.PROPERTY,
            "com.sun.org.apache.xerces.internal.dom.DOMImplementationSourceImpl");
    DOMImplementationRegistry domImplementationRegistry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS domImplementation = (DOMImplementationLS) domImplementationRegistry
            .getDOMImplementation("LS");
    LSInput lsInput = domImplementation.createLSInput();
    InputStream xmlInputStream = xmlFile.getInputStreamForReading();
    lsInput.setByteStream(xmlInputStream);
    LSParser lsParser = domImplementation.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
    DOMConfiguration domConfig = lsParser.getDomConfig();
    if(domConfig.canSetParameter("validate-if-schema", Boolean.FALSE) && domConfig.canSetParameter("validate", Boolean.FALSE)){
        domConfig.setParameter("validate-if-schema", Boolean.FALSE);
        domConfig.setParameter("validate", Boolean.FALSE);
    }
    xmlDocument = lsParser.parse(lsInput);
    if (oldValue != null) {
        System.setProperty(DOMImplementationRegistry.PROPERTY, oldValue);
    }

我遇到的问题是,在parse上调用lsParser时会抛出org.w3c.dom.ls.LSException。关于DTD验证,我只找到了停用验证的信息w.r.t. DocumentBuilderFactory以下列方式:

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory .setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

但遗憾的是没有与LSParser相关联。这怎么可以实现?

0 个答案:

没有答案