Java tutorial
//package com.java2s; 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.StreamResult; import javax.xml.transform.stream.StreamSource; public class Main { /** * @param xml * @return pretty xml */ public static String prettyXml(String xml) { TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer serializer; try { Source source = new StreamSource(new StringReader(xml)); StringWriter writer = new StringWriter(); serializer = tfactory.newTransformer(); // Setup indenting to "pretty print" serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); serializer.transform(source, new StreamResult(writer)); return writer.toString(); } catch (Exception e) { return xml; } } }