Question

I need to parse XML document, which starts with following lines:

<?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"/>

I read it using following code:

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

    builder = builderFactory.newDocumentBuilder();

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

The last call fails with following exception:

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)

File pdf2xml.dtd actually doesn't exist in the specified directory.

How can I modify the code so that the document is parsed despite the absence of pdf2xml.dtd ?

Was it helpful?

Solution

You need to use 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;
    }
});

when the parser reaches the condition - "pdf2xml.dtd", the entity resolver is called, which returns an empty XML doc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top