Prevent DTD loading when using XSLT, i.e. XML Transformer

I need to process XML files with DTDs with XSLT in Java. DTD is really necessary because it contains the definitions of the objects that I use. (aside: yes, using entities for things that can use unicode is a bad idea ;-)

When I start the conversion, it loads the DTD from an external source every time. I want it to use the XML directory for DTD caching, so I gave TransformerFactory a CatalogResolver as URIResolver :

 URIResolver cr = new CatalogResolver(); tf = TransformerFactory.newInstance(); tf.setURIResolver(cr); Transformer t = tf.newTransformer(xsltSrc); t.setURIResolver(cr); Result res = new SAXResult(myDefaultHandler()); t.transform(xmlSrc, res); 

But when I start the conversion, it still loads the DTD over the network. (Using Xalan and Xerces is either part of Java5, or standalone, or using Saxon and Xerces.)

What is required to force the conversion to use only a local copy of the DTD?

+7
java xml xslt
source share
2 answers

(I answer my question here in order to save me next time, or anyone else, in the days of messing around, I needed to find the answer.)

Actually, you need to change the way you eliminate DTD: EntityResolver . Unfortunately, you cannot install EntityResolver to use Transformer . So, first you need to create an XMLReader with CatalogResolver as EntityResolver :

 SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); XMLReader r = spf.newSAXParser().getXMLReader(); EntityResolver er = new CatalogResolver(); r.setEntityResolver(er); 

and use it for Transformer :

 SAXSource s = new SAXSource(r, xmlSrc); Result res = new SAXResult(myDefaultHandler()); transformer.transform(s, res); 
+10
source share

You can use this code to disable this feature in Xerces:

 org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader(); reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); 

This code example uses Dom4j, but a similar setFeature function exists in other XML java libraries such as JDOM.

+3
source share

All Articles