Alex Rivera | Logout

Parsing an XML file with a DTD schema on a relative path

Asked 2011-01-18T16:12:58.483
11

I have the following java code:


DocumentBuilder db=DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc=db.parse(new File("/opt/myfile"));

And /opt/myfile contains something like:

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

I get the following error:

java.io.FileNotFoundException: /../schema/xml/schema.dtd (No such file or directory)

This is a large java framework that consumes an XML file produced elsewhere. I think the relative path is the problem. I don't think it will be acceptable to change the cwd before the JVM starts (the path comes from a config file that is read by the JVM itself) and I have not found a way to change the cwd while the JVM is running. How do I parse this XML file with the appropriate DTD?

Edit
Report

1 Answer

20

You need to use a custom EntityResolver to tweak the path of the DTD so that it can be found. For example:

db.setEntityResolver(new EntityResolver() {
    @Override
    public InputSource resolveEntity(String publicId, String systemId)
            throws SAXException, IOException {
        if (systemId.contains("schema.dtd")) {
            return new InputSource(new FileReader("/path/to/schema.dtd"));
        } else {
            return null;
        }
    }
});

If schema.dtd is on your classpath, you can just use getResourceAsStream to load it, without specifying the full path:

return new InputSource(Foo.class.getResourceAsStream("schema.dtd"));
answered 2011-01-18T16:37:10.657

Your Answer