【问题标题】:Disallow entity declarations but allow DTDs不允许实体声明,但允许 DTD
【发布时间】:2015-07-08 20:20:04
【问题描述】:

我收到一个必须允许具有文档类型声明 (DTD) 的 XML 文档,但我们禁止任何实体声明。

SAXParser.parse()解析XML文档,如下:

SAXParserFactory factory = SAXParserFactory.newInstance();

factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
factory.setValidating(true);

SAXParser parser = factory.newSAXParser();

XML 然后作为InputSource 传递到解析器:

InputSource inputSource= ... ;
parser.parse(inputSource, handler);

handler 有一个resolveEntity 方法,SAXParser.parse() 调用:

public InputSource resolveEntity(String pubID, String sysID) throws SAXException {
  InputSource inputSource = null;
  try {
     inputSource = entityResolver.resolveEntity(publicId, systemId);
  }
  catch (IOException e) {
     throw new SAXException(e);
  }
  return inputSource;
}

当我传入一个带有 ENTITY 引用的 XML 文件时,似乎什么都没做 - 没有抛出异常,也没有任何内容被剥离 - 或关于被禁止的 ENTITY 引用。

这是我正在使用的错误 XML 的示例。应该允许 DTD,但不允许使用 !ENTITY 行:

<!DOCTYPE foo SYSTEM "foo.dtd" [
    <!ENTITY gotcha SYSTEM "file:///gotcha.txt"> <!-- This is disallowed-->
]>

<label>&gotcha;</label>

我需要做些什么来确保在 XML 中不允许 ENTITY 引用,但仍然允许 DTD?

【问题讨论】:

    标签: java xml sax saxparser


    【解决方案1】:

    在 SaxParser 上设置 org.xml.sax.ext.DeclHandler

    parser.setProperty("http://xml.org/sax/properties/declaration-handler", myDeclHandler);
    

    当解析内部实体声明时,DeclHandler 会收到通知。要禁止实体声明,您可以简单地抛出 SAXException:

    public class MyDeclHandler extends org.xml.sax.ext.DefaultHandler2 {
         public void internalEntityDecl(String name, String value) throws SAXException {
             throw new SAXException("not allowed");
         }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      • 2015-02-20
      • 1970-01-01
      • 1970-01-01
      • 2014-01-19
      • 1970-01-01
      相关资源
      最近更新 更多