Categories
Java

Java 1.5 bug – Transfromer needs some coaxing

Java 1.5’s built-in JAXP implementation has a Transformer object that does not indent despite being asked to do so. This is how to force it to do so…

Share

My current class assignment requires me to produce XML. Not so wisely I am using DOM to build the Document, but then the benefit comes in the form of Java’s Transformer object. What a fine object it is – the one and only meant to commit your XML to a file.
Still, what used to work in Java 1.4 somehow broke in Java 1.5; Transformer no longer obeys the following instructions that are meant to set it to indent its XML output:

TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT,"yes");

Naturally, I Googled this issue and as usual, the best place to find an answer were the Sun Java Forums. Many people offered help but the one that actually cracked this problem was one xuemingshen in this thread: His solution — use an OutputStreamWriter object as the parameter for the StreamResult that will be used by the Transfomer when it performs the transformation. The code:


try
{
Source source = new DOMSource(myDOMDocument);
File outputFile = new File(fileName + ".xml");
FileOutputStream outputStream = new FileOutputStream(outputFile);
Result result = new StreamResult(new OutputStreamWriter(outputStream));

TransformerFactory factory = TransformerFactory.newInstance();
factory.setAttribute("indent-number", 4);

Transformer transformer = factory.newTransformer();

transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT,"yes");

transformer.transform(source, result);
}

catch… TransformerConfigurationException, TransformerException, FileNotFoundException

I am using a FileOutputStream object to output to file but an OutputStream object will do.
Thank you xuemingshen !

Share

Leave a Reply

Your email address will not be published. Required fields are marked *

 

Share