Here you can find the source of prettyFormat(String input)
Parameter | Description |
---|---|
input | XML input to format. |
Parameter | Description |
---|---|
TransformerException | if some problem occur while processing the xml |
public static String prettyFormat(String input) throws TransformerException
//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 { /**//from w ww . j a v a 2 s . com * 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; } }