Wednesday, July 25, 2012

java pretty print xml

Java 6 already has the transformer which can print xml in a pretty way.

public class XmlPrettyPrint {
public static String getPrettyXml(String xmlStr) throws TransformerException {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", 4);
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult result = new StreamResult(new StringWriter());
StreamSource source = new StreamSource(new StringReader(xmlStr));
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
return xmlString;
}

public static void main(String[] args) throws TransformerException {
String xmlStr = "<root><child><sub>ddd</sub></child><child/></root>";
System.out.println(XmlPrettyPrint.getPrettyXml(xmlStr));
}
}


The result is



<?xml version="1.0" encoding="UTF-8"?>
<root>
    <child>
        <sub>ddd</sub>
    </child>
    <child/>
</root>

No comments:

Post a Comment