解决方式整合一下,就分两种:
1、用setFeature()
SAXReader reader = new SAXReader();
reader.setValidation(false); reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
...
2、用setEntityResolver()
SAXReader reader = new SAXReader();
reader.setValidation(false); reader.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return new InputSource(new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes())); } });
...
这个问题,平时不会去注意,这次记录的主要原因是,在做自定义xml文件解析成key-vlue的形式时,发现时间略长,影响体验,故而mark一下。
参考:
setFeature的妙用,解析XML时,外部注入预防即XXE攻击
http://xerces.apache.org/xerces-j/features.html
XML防止XXE攻击
描述
https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing
解决方案:
https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet
https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#SAXReader
参考:
结合来做就是:
spf.setFeature("http://xml.org/sax/features/external-general-entities", false); spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);