评估 xpath 时禁止 DTD

Disallow DTD's while evaluating xpath

我有以下代码来评估 xpath 表达式。

String inputXml = "<?xml version=\"1.0\"?><!DOCTYPE document SYSTEM   \"test.dtd\"><Request><Header><Version>1.0</Version></Header></Request>";

String xpath="/Request/Header/Version";

XPathFactory xpf = new net.sf.saxon.xpath.XPathFactoryImpl();
final InputSource is = new InputSource(new StringReader(inputXml));
String version = xpf.newXPath().evaluate(xpath, is);

xpf.newXPath().evaluate 抛出错误 test.dtd couldn't be found。我想完全禁止 DTD。我一直在阅读有关设置 SAXParser 功能“http://apache.org/xml/features/disallow-doctype-decl”的信息,但不确定如何在这种情况下应用,或者是否有任何其他方法可以实现 disallow/ignore DTD。

我不太确定你想要达到什么目的。如果您希望它因为引用了 DTD 而失败,那么您似乎已经实现了这一目标。

但是,如果您想在 XML 解析器上设置 属性,有两种方法可以实现:

(a) 提供 SAXSource 而不是 InputSource;将SAXSource中的XMLReader初始化为你要使用的XML解析器,在传递给XPath引擎之前使用XMLReader的setFeature接口进行配置。

(b) 将 Saxon 配置功能 http://saxon.sf.net/feature/parserFeature?uri=http://apache.org/xml/features/disallow-doctype-decl(即没有空格或换行符的单个字符串)设置为值 true。您可以使用

xpf.getConfiguration().setConfigurationProperty(featureName, true);