Wednesday, May 1, 2013

Pretty-print XML using Java

This can be done by using the javax.xml.transform package as follows:
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.*;

...

public static String prettyFormat(String input, int indent) {
 try {
     Source xmlInput = new StreamSource(new StringReader(input));
     StringWriter stringWriter = new StringWriter();
     StreamResult xmlOutput = new StreamResult(stringWriter);
     TransformerFactory transformerFactory = TransformerFactory.newInstance();
     Transformer transformer = transformerFactory.newTransformer(); 
     transformer.setOutputProperty(OutputKeys.INDENT, "yes");
     transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent));
     transformer.transform(xmlInput, xmlOutput);
     return xmlOutput.getWriter().toString();
 } catch (Exception e) {
     e.printStackTrace();
     return null;
 }
}
Ref:
http://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java

2 comments:

LVM said...

So many complicated solutions out there, this one is simple and requires no 3rd party libs. It worked well for me, thanks. I did see one issue, a newline is needed before the root node because right now it prints on the same line as the declaration, like:

LVM said...

Oops, let me try again (with escaping :)):

\\