Pretty print XML document

I use the following XMLHelper.java code whenever i have a requirement to pretty print XML, it can handle String, Document and Source, the common objects that i need to print


package com.webspherenotes.xml;

import java.io.OutputStream;
import java.io.StringReader;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;

public class XMLHelper {

  public static void prettyPrintXML(Source source, OutputStream stream) {
    try {
      Transformer transformer = TransformerFactory.newInstance()
          .newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.
   setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
      transformer.transform(source, new StreamResult(stream));
    } catch (Exception e) {
      e.printStackTrace(System.out);
    }
  }
  
  public static void prettyPrintXML(Document doc, OutputStream stream) {
    prettyPrintXML(new DOMSource(doc),stream);
  }
  
  public static void prettyPrintXML(String xmlString, OutputStream stream){
    prettyPrintXML(new StreamSource(new StringReader(xmlString)),stream);
  }
}

No comments: