在评估xpath时禁止DTD

时间:2016-05-26 03:46:00

标签: xpath saxon

我有以下代码来评估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功能&#34; http://apache.org/xml/features/disallow-doctype-decl&#34;但不知道如何在这种情况下申请或有任何其他方式来禁止/忽略DTD。

1 个答案:

答案 0 :(得分:0)

我不太清楚你想要达到什么目标。如果您因为引用了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);