Here you can find the source of prettyFormat(String strInput, int nIndent)
Parameter | Description |
---|---|
strInput | Valid XML document (No validity check yet!) |
nIndent | Indent |
Parameter | Description |
---|---|
Exception | in error case |
public static String prettyFormat(String strInput, int nIndent) throws Exception
//package com.java2s; //License from project: Apache 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.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; public class Main { /**/*w w w . j a va 2 s.c o m*/ * Pretty format a given XML document * * @param strInput * Valid XML document (No validity check yet!) * @param nIndent * Indent * @return Formatted XML document * @throws Exception * in error case */ public static String prettyFormat(String strInput, int nIndent) throws Exception { try { Source xmlInput = new StreamSource(new StringReader(strInput)); StringWriter stringWriter = new StringWriter(); StreamResult xmlOutput = new StreamResult(stringWriter); TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", nIndent); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(nIndent)); transformer.transform(xmlInput, xmlOutput); return xmlOutput.getWriter().toString(); } catch (Exception e) { // Logger.XMLEval.logState("Pretty formatting: " + e.getMessage(), LogLevel.Error); throw e; } } /** * Pretty format a given XML document with indent of 2 * * @param strInput * Valid XML document (No validity check yet!) * @return Formatted XML document * @throws Exception * in error case */ public static String prettyFormat(String strInput) throws Exception { return prettyFormat(strInput, 2); } }