Tuesday, May 31, 2011

XML Pretty Printing Without External Dependencies

This code uses javax.xml.transform to perform a simple XSL transformation to pretty print a given XML as a string. Hope someone will find this useful.

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import javax.xml.transform.*;
import javax.xml.transform.stream.*;

public class XMLPrettyPrinter {
 
 public static void main(String[] args) {
  new XMLPrettyPrinter().demo();
 }

 private void demo() {
  String input = "info";
  String output = new String();
  try {
   output = this.prettify(input);
  } catch (Exception e) {
  }
  System.out.println("Input XML:\n" + input);
  System.out.println("\nOutput XML:\n" + output);
 }

 private String prettyPrintStylesheet = 
    ""
  + "  "
  + "  "
  + "  "
  + "    "
  + "  "
  + "  "
  + "        "
  + "          "
  + "        " 
  + "  " 
  + "";
 
 public String prettify(String inputXML) throws Exception {

  Source stylesheetSource = new StreamSource(new ByteArrayInputStream(
    prettyPrintStylesheet.getBytes()));

  Source xmlSource = new StreamSource(new ByteArrayInputStream(
    inputXML.getBytes()));
  ByteArrayOutputStream out = new ByteArrayOutputStream();

  TransformerFactory tf = TransformerFactory.newInstance();
  Templates templates = tf.newTemplates(stylesheetSource);
  Transformer transformer = templates.newTransformer();
  transformer.transform(xmlSource, new StreamResult(out));
  return out.toString();
 }

}

No comments: