Wednesday, August 8, 2007

XML Transformer indent doesn't work with jdk5

The below code works fine with jdk1.4, i can get nice formatted xml document.



TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource source = new DOMSource(document);
StreamResult stream = new StreamResult(os);
transformer.transform(source, stream);



However, found it doesn't work on jdk5.
I need to change to the following work around code



TransformerFactory transFactory = TransformerFactory.newInstance();
transFactory.setAttribute("indent-number",
new Integer(2));
Transformer transformer = transFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(new DOMSource(document),
new StreamResult(new OutputStreamWriter(os, "utf-8")));

10 comments:

Anonymous said...

Hi there!

many thanks for this post. I had no problem to solve about the output stream configuration (utf-8), but for me the "indent" didn't work at all. Here I learned about the

transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

and now the world is wunderbar again. :-)

Anonymous said...

Hey!
Your post helped me a lot^^
Thanks!

Anonymous said...

See also http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6337981

Anonymous said...

it is very funny how you express it worked with 1.4 does not work with 1.5

Even the new posted solution does not work with "my 1.5 runtime"
ane even old code "did not work" with my 1.4 runtime.

You should be more specific about exact version of Factorie and transformer implementation classes and tehir version folks ;-)

Unknown said...

Hi,

Using the OutputStreamWriter works!..Thank you

Unknown said...

Yes, finally OutputStreamWriter worked! (use Java 1.5)

Racumin said...

This worked for me. Thanks a lot!

transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

r13mus said...

thanks a lot

Anonymous said...

Where is the os variable declared?

Anonymous said...

In JDK 6, I just needed to add this line to the transformer: transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");