Java HTML / XML How to - Do Pretty Printing with Transformer








Question

We would like to know how to do Pretty Printing with Transformer.

Answer

import java.io.StringReader;
//from  w  w  w. j ava 2  s .com
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class Main {

  public static void main(String[] args) throws Exception {

    String xmlSample = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><tag><nested>hello</nested></tag>";
    String stylesheet = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:output method=\"xml\" version=\"1.0\" indent=\"yes\"/><xsl:template match=\"node()|@*\"><xsl:copy><xsl:apply-templates select=\"node()|@*\"/></xsl:copy></xsl:template></xsl:stylesheet>";

    TransformerFactory factory = TransformerFactory.newInstance();

    Source xslSource = new StreamSource(new StringReader(stylesheet));
    Transformer transformer = factory.newTransformer(xslSource);

    Source source = new StreamSource(new StringReader(xmlSample));
    Result result = new StreamResult(System.out);

    transformer.transform(source, result);

  }

}