在Java中解析XML文件时如何避免读取DTD?

时间:2014-04-18 18:20:27

标签: java xml xml-parsing

我需要解析XML文档,该文档从以下行开始:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE pdf2xml SYSTEM "pdf2xml.dtd">

<pdf2xml producer="poppler" version="0.22.0">
<page number="1" position="absolute" top="0" left="0" height="1263" width="892">
    <fontspec id="0" size="12" family="Times" color="#000000"/>

我使用以下代码阅读:

    final DocumentBuilder builder;
    DocumentBuilderFactory builderFactory =
            DocumentBuilderFactory.newInstance();

    builder = builderFactory.newDocumentBuilder();

    Document document = builder.parse(
            new FileInputStream(aXmlFileName));

最后一次调用失败,出现以下异常:

Exception in thread "main" java.io.FileNotFoundException: D:\dev\ro-2014-04-13-01\pdf2xml.dtd
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:146)
    at java.io.FileInputStream.<init>(FileInputStream.java:101)
    at sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:90)
    at sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:188)
    at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:613)

文件pdf2xml.dtd实际上并不存在于指定的目录中。

如何修改代码,以便在没有pdf2xml.dtd的情况下解析文档?

1 个答案:

答案 0 :(得分:4)

您需要使用Entity Resolver

 myBuilder.setEntityResolver(new EntityResolver() {
    @Override
    public InputSource resolveEntity(String publicId, String systemId)
            throws SAXException, IOException {
        if (systemId.contains("pdf2xml.dtd")) {
            return new InputSource(new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes()));
        } else
           return null;
    }
});

当解析器达到条件 - &#34; pdf2xml.dtd&#34;时,将调用实体解析器,返回一个空的XML文档。