User Tools

Site Tools


pretty_print_xml

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

pretty_print_xml [2014/03/06 09:23] (current)
mihael created
Line 1: Line 1:
 +====== Pretty Print XML in Java ======
 +There are several ways to pretty print XML in Java.
  
 +===== Using Xerces =====
 +<sxh java>
 +    public static String format(String unformattedXml) {
 +        try {
 +            final Document document = parseXml(unformattedXml);​
 +
 +            OutputFormat format = new OutputFormat(document);​
 +            format.setLineWidth(65);​
 +            format.setIndenting(true);​
 +            format.setIndent(2);​
 +            Writer out = new StringWriter();​
 +            XMLSerializer serializer = new XMLSerializer(out,​ format);
 +            serializer.serialize(document);​
 +
 +            return out.toString();​
 +        } catch (IOException e) {
 +            throw new RuntimeException(e);​
 +        }
 +    }
 +
 +    private static Document parseXml(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);​
 +        }
 +    }
 +</​sxh>​
 +
 +===== Using Standard Java Library =====
 +<sxh java>
 +public static String prettyFormat(String input, int indent) {
 +    try {
 +        Source xmlInput = new StreamSource(new StringReader(input));​
 +        StringWriter stringWriter = new StringWriter();​
 +        StreamResult xmlOutput = new StreamResult(stringWriter);​
 +        TransformerFactory transformerFactory = TransformerFactory.newInstance();​
 +        transformerFactory.setAttribute("​indent-number",​ indent);
 +        Transformer transformer = transformerFactory.newTransformer(); ​
 +        transformer.setOutputProperty(OutputKeys.INDENT,​ "​yes"​);​
 +        transformer.transform(xmlInput,​ xmlOutput);
 +        return xmlOutput.getWriter().toString();​
 +    } catch (Exception e) {
 +        throw new RuntimeException(e);​ // simple exception handling, please review it
 +    }
 +}
 +
 +public static String prettyFormat(String input) {
 +    return prettyFormat(input,​ 2);
 +}
 +</​sxh>​
 +
 +From http://​stackoverflow.com/​questions/​139076/​how-to-pretty-print-xml-from-java
 +
 +{{tag>​devel java}}
pretty_print_xml.txt ยท Last modified: 2014/03/06 09:23 by mihael