×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
1
Language: Java
Posted by: Gerrit Viljoen
Added: Apr 30, 2014 1:00 PM
Modified: May 8, 2014 1:12 PM
Views: 32
Quick and dirty XML pretty print.

No third party libs.
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
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 org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
  1.     public static String prettyPrintXML(String xml) {
  2.         if (xml == null) {
  3.             return null;
  4.         }
  5.  
  6.         try {
  7.             DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  8.             DocumentBuilder db = dbf.newDocumentBuilder();
  9.             InputSource is = new InputSource(new StringReader(xml));
  10.             Document doc = db.parse(is);
  11.  
  12.             TransformerFactory tf = TransformerFactory.newInstance();
  13.             Transformer transformer = tf.newTransformer();
  14.             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
  15.             transformer.setOutputProperty(OutputKeys.METHOD, "xml");
  16.             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
  17.             transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
  18.             transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
  19.  
  20.             ByteArrayOutputStream writer = new ByteArrayOutputStream();
  21.             transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(writer, "UTF-8")));
  22.             return writer.toString();
  23.         } catch (IOException e) {
  24.             throw new RuntimeException(e);
  25.         } catch (ParserConfigurationException e) {
  26.             throw new RuntimeException(e);
  27.         } catch (SAXException e) {
  28.             throw new RuntimeException(e);
  29.         } catch (TransformerException e) {
  30.             throw new RuntimeException(e);
  31.         }
  32.     }