I'm a student at the Free University of Berlin. I enjoy hacking and messing about with LaTeX.

In case you should whish to contanct me you can do so at carlos@cmartin.tk. To subscribe RSS 2.0 feed

 

Not loading a file’s DTD when doing an XSL Transformation in Java

This has hit me in the face two or three times already in the same project, and last time I solved it by calling /usr/bin/xsltproc --html from inside the servlet. Finally I’ve found a way to tell the underlying levels not to bother loading the DTD as it’s useless and doesn’t even live where the XML file thinks it does.

This problem was not helped by the JVM’s limitations, namely, its inability to change the process’ working directory.

Without further ado, this is the code that transforms an XML file with DTD without trying to load it. The important parts are factory.setValidating(false); and factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); which I’m pretty sure I had tried several times before, but it has only worked this time.

String xslPath = getServletContext().getRealPath("content.xsl");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
try {
	factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
} catch (ParserConfigurationException e2) {
	// TODO Auto-generated catch block
	e2.printStackTrace();
}
DocumentBuilder builder = null;
try {
	builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e1) {
	// TODO Auto-generated catch block
	e1.printStackTrace();
}
InputSource src = new InputSource(item.getInputStream());
Document xmlDocument = null;
try {
	xmlDocument = builder.parse(src.getByteStream());
} catch (SAXException e1) {
	// TODO Auto-generated catch block
	e1.printStackTrace();
}
DOMSource xmlSource = new DOMSource(xmlDocument);
TransformerFactory transFact = TransformerFactory.newInstance();
Result result = new StreamResult(out);
Source xslSource = new StreamSource(xslPath);
try {
	Transformer transformer = transFact.newTransformer(xslSource);
	transformer.transform(xmlSource, result);
} catch (TransformerConfigurationException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
} catch (TransformerException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}

Tags: , , , , ,

Filed under:hacking

Leave a Reply