How to format xml using Java

The java development kit contains the javax.xml.transform package to manipulate xml content. The transformer object takes in input a stream that contains the XML. The transformer applies the transformation using the transform method.


This example creates an input String that holds xml that is not indented. Then it creates a Transformer using the TransformerFactory. The transformer is configured to indent the xml. The size of the indentation is 2. The transform method is called, the output of process is written in System.out. If an error occures like the xml being invalid, the error message is also witten in the ouput.


import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;

public class XmlFormatter {

    public static void main(String[] argv) {

	final String input = "<a><b>test</b><c>test2</c></a>"; xmlResultResource = new;
	Transformer xmlTransformer = null;
	try {
	    xmlTransformer = TransformerFactory.newInstance().newTransformer();

	    xmlTransformer.setOutputProperty("{}indent-amount", "2");
	    xmlTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
	} catch (TransformerConfigurationException e) {
	    System.out.println( "Transformer configuration error: " + e.getMessage() );

	try {
	    xmlTransformer.transform(new StreamSource(new StringReader(input)),
		    new StreamResult(xmlResultResource));
	} catch (TransformerException e) {
	    System.out.println("Error transform: " + e.getMessage());

	final String output = xmlResultResource.getBuffer().toString();

	System.out.println( "input:" );
	System.out.println( input  );

	System.out.println( "output:" );
	System.out.println( output  );


The output will be:

<?xml version="1.0" encoding="UTF-8"?><a>


XML Wikipedia

Recent Comments