How can I include a DTD in an XML file to 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 the JAR actually) at the time the Servlet is initialized using:

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

      

The XML is found correctly, but for a DTD in the same package, Xerces gives me a FileNotFoundException and displays the path to run Tomcat script with "videofaq.dtd" appended to the end. What hints, if any, can be passed to Xerces so that it loads the DTD correctly?

0


source to share


4 answers


A custom EntityResolver will work, but you can avoid having to create your own class by setting the 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 the 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 where the processor cannot resolve this URI. A simple fix is ​​to call the setSystemId () method like this:

// 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);

      

+1


source


When you do

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

      

It is not the xerones that you call and as such, when you stream to the xers, it cannot know where the file is loaded from. It downloads it from the root path of the application (which you described).

A simple solution would be to list the entire path in your XML file to dtd.



Also, xerces tries to try multiple locations. Therefore, you should take a look at the grammar caching engine or entity recognizers (which are used in that order I think).

Xerces grammar doc: http://xerces.apache.org/xerces2-j/faq-grammars.html

Xerces use-entity-resolver2 functions: http://xerces.apache.org/xerces2-j/features.html

+1


source


When using SAX, you can provide your own EntityResolver

, which then loads the resource any way you want .

0


source


In general, try using method overloads that take a URL (usually as a String with a parameter name such as "systemId") when specifying input to parse XML. This allows the parser to resolve relative links for you and provide better error messages.

So, in your case, find the DTD in the same package with videofaq.xml and pass the result String

getClass().getResource("videofaq.xml")

to the XML parser.

0


source







All Articles