Tuesday, August 7, 2012

Formating XML for Pretty Printing

The following Class is an example which we can use to Pretty Printing XML.

method parseXmlString() reads a String and build a Document Object.
method formatXMLString() uses Transformer Object's Outputproperties to set features like Encoding, Indentation etc.
public class XmlFormatter { public String formatXMLString(String string) throws Exception { final Document document = parseXmlString(string); Transformer tf = TransformerFactory.newInstance().newTransformer(); tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tf.setOutputProperty(OutputKeys.INDENT, "no"); tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); Writer out = new StringWriter(); tf.transform(new DOMSource(document), new StreamResult(out)); return out.toString(); } private Document parseXmlString(String in) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(in)); return db.parse(is); } catch (ParserConfigurationException e) { throw new RuntimeException(e); } catch (SAXException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }

No comments :

Post a Comment