Java HTML / XML How to - Pretty print XML with transform








Question

We would like to know how to pretty print XML with transform.

Answer

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
/*from  w  w w.  j  av a2  s  .  c o  m*/
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.InputSource;

public class Main {
  public static void main(String[] args) throws Exception {
    Transformer serializer = SAXTransformerFactory.newInstance()
        .newTransformer();
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",
        "2");
    serializer.setOutputProperty("{http://xml.customer.org/xslt}indent-amount",
        "2");
    Source xmlSource = new SAXSource(new InputSource(new ByteArrayInputStream(
        "<a><b><c/><d>text D</d><e value='0'/></b></a>".getBytes())));
    StreamResult res = new StreamResult(new ByteArrayOutputStream());
    serializer.transform(xmlSource, res);
    System.out.println(new String(((ByteArrayOutputStream) res
        .getOutputStream()).toByteArray()));
  }
}