Here you can find the source of xmlFormat(String xml)
private static String xmlFormat(String xml)
//package com.java2s; //License from project: Apache License import java.io.StringReader; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.xml.sax.InputSource; public class Main { private static String xmlFormat(String xml) { StringWriter writer;// w w w . j av a 2s .co m try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; db = dbf.newDocumentBuilder(); Document doc = db.parse(new InputSource(new StringReader(xml))); DOMSource source = new DOMSource(doc); writer = new StringWriter(); Result result = new StreamResult(writer); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(source, result); return (writer.getBuffer().toString()); } catch (Exception e) { e.printStackTrace(); } return null; } }