Java tutorial
//package com.java2s; //License from project: Open Source License 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.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; public class Main { /** * Format the provided XML input with a default indentation of <i>2</i>. * * @param input * XML input to format. * @return Formatted XML. * @throws TransformerException * if some problem occur while processing the xml * @see #prettyFormat(String, int) */ public static String prettyFormat(String input) throws TransformerException { return prettyFormat(input, 2); } /** * Format the provided XML input. * * @param input * XML input to format. * @param indent * Indentation to use on formatted XML. * @return Formatted XML. * @throws TransformerException * if some problem occur while processing the xml * @see #prettyFormat(String) */ public static String prettyFormat(String input, Integer indent) throws TransformerException { if (input != null) { 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 == null ? 2 : indent)); transformer.transform(xmlInput, xmlOutput); return xmlOutput.getWriter().toString(); } return input; } }