1.4 XML读写

1.4.1【必须】XML解析器关闭DTD解析

读取外部传入XML文件时,XML解析器初始化过程中设置关闭DTD解析。

参考示例:

javax.xml.parsers.DocumentBuilderFactory

  1. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  2. try {
  3. dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
  4. dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
  5. dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
  6. dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
  7. dbf.setXIncludeAware(false);
  8. dbf.setExpandEntityReferences(false);
  9. ……
  10. }

org.dom4j.io.SAXReader

  1. saxReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
  2. saxReader.setFeature("http://xml.org/sax/features/external-general-entities", false);
  3. saxReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);

org.jdom2.input.SAXBuilder

  1. SAXBuilder builder = new SAXBuilder();
  2. builder.setFeature("http://apache.org/xml/features/disallow-doctype-decl",true);
  3. builder.setFeature("http://xml.org/sax/features/external-general-entities", false);
  4. builder.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
  5. Document doc = builder.build(new File(fileName));

org.xml.sax.XMLReader

  1. XMLReader reader = XMLReaderFactory.createXMLReader();
  2. reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
  3. reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
  4. reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
  5. reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);