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.

Example:

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 java.io.StringReader;

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;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class XmlFormatter {

    public static void main(String[] argv) {

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

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

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

	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:

input:
<a><b>test</b><c>test2</c></a>
output:
<?xml version="1.0" encoding="UTF-8"?><a>
  <b>test</b>
  <c>test2</c>
</a>


References:

XML Wikipedia

Share this article:

Recent Comments