Search code examples
javaxmlxerces

How do I include a DTD in an XML file that will be loaded using getResourceAsStream()?


I have an xml file ('videofaq.xml') that defines a DTD using the following DOCTYPE

<!DOCTYPE video-faq SYSTEM "videofaq.dtd">

I am loading the file from the classpath (from a JAR actually) at Servlet initialization time using:

getClass().getResourceAsStream("videofaq.xml")

The XML is found correctly, but for the DTD in the same package, Xerces gives me a FileNotFoundException, and displays the path to the Tomcat startup script with "videofaq.dtd" appended to the end. What hints, if any, can I pass on to Xerces to make it load the DTD properly?


Solution

  • A custom EntityResolver will work, but you might be able to avoid having to create a custom class by setting a SystemID to allow the processor to "find" relative paths.

    http://www.onjava.com/pub/a/onjava/excerpt/java_xslt_ch5/index.html?page=5

    By providing a system identifier as a parameter to the StreamSource, you are telling the XSLT processor where to look for commonFooter.xslt. Without this parameter, you may encounter an error when the processor cannot resolve this URI. The simple fix is to call the setSystemId( ) method as follows:

    // construct a Source that reads from an InputStream
    Source mySrc = new StreamSource(anInputStream);
    // specify a system ID (a String) so the 
    // Source can resolve relative URLs
    // that are encountered in XSLT stylesheets
    mySrc.setSystemId(aSystemId);