Thursday, January 5, 2012

Pretty Format XML in Java

I've been playing with Amazon Product Advertising API for a while. One of the pain is reading the xml response, it's all in one line and I have to scroll to find useful information. Then I began to create a xml file and copy the response string into this file, using Eclipse's auto format this xml file. It's still painful when there are a lot of request need to try. So I brought this pretty xml formatter to ease the pain. And you don't need other library more than JDK.

First of all, we need the pretty-print.xsl stylesheet to indicate the format we want to be transformed.


 
 
 
 
 
  
   
  
 



Let's transform:
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
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;
import org.xml.sax.SAXException;

public class XmlUtils {

 public static String perttyFormat(String xml) {

  // 1. remove new line and tab characters
  // since Transformer will ignore those characters in elements
  xml = xml.replaceAll("\t", "");
  xml = xml.replaceAll("\n", "");

  try {
   // 2.Parse this xml into Documnet
   DocumentBuilder documentBuilder = DocumentBuilderFactory
     .newInstance().newDocumentBuilder();
   InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
   Document document = documentBuilder.parse(inputStream);

   // 3.Build Transformer
   // place pretty-print.xsl in the same package as this class
   // Note that a stylesheet is needed to make formatting reliable.
   String path = XmlUtils.class.getResource("pretty-print.xsl")
     .getPath();
   TransformerFactory transformerFactory = TransformerFactory
     .newInstance();
   Transformer transformer = transformerFactory
     .newTransformer(new StreamSource(path));
   StringWriter stringWriter = new StringWriter();
   StreamResult streamResult = new StreamResult(stringWriter);
   DOMSource domSource = new DOMSource(document);
   transformer.transform(domSource, streamResult);
   return stringWriter.toString();
  } catch (ParserConfigurationException e) {
   e.printStackTrace();
  } catch (TransformerException e) {
   e.printStackTrace();
  } catch (SAXException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }

  return null;
 }

}

Refrence:
http://www.chipkillmar.net/2009/03/25/pretty-print-xml-from-a-dom/