How to Indent XML String in Java (Pretty)

We often need to format a text block in xml to better visualize its content, after all we are human, aren’t we? In this post, we demonstrate a block of source code in java that does this job for us … I particularly use it a lot to inspect the request and response of a WebService in Soap … erghhh Soap. I know … But sometimes it is necessary … Have fun

This is a cool way to prettify your XML (String format) in Java Language:

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class FormatXML {

	public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException {
		System.out.println(format("YOUR_XML_HERE", true));
	}

	public static String format(String xml, Boolean ommitXmlDeclaration) throws IOException, SAXException, ParserConfigurationException {

		DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Document doc = db.parse(new InputSource(new StringReader(xml)));

		OutputFormat format = new OutputFormat(doc);
		format.setIndenting(true);
		format.setIndent(2);
		format.setOmitXMLDeclaration(ommitXmlDeclaration);
		format.setLineWidth(Integer.MAX_VALUE);
		Writer outxml = new StringWriter();
		XMLSerializer serializer = new XMLSerializer(outxml, format);
		serializer.serialize(doc);

		return outxml.toString();

		}

}