Friday, 7 October 2016

Formatting or preety printing XML and JSON in Java


XML as we know is a platform independent format that can be used to communicate between different apps. We have seen couple of things on XML like parsing, handling special characters, java library etc (See links in Related Links section below). In this post we will see how we can format or preety print xml in Java.

To the code... preety printing XML

Following code will do the trick -

    private static String beautifyXml(String unformattedXML) {
        Transformer transformer;
        String formattedXmlString = null;
        try {
            transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{}indent-amount", "2");
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            //initialize StreamResult with File object to save to file
            StreamResult result = new StreamResult(new StringWriter());
            transformer.transform(new StreamSource(new StringReader(unformattedXML)), result);
            formattedXmlString = result.getWriter().toString();
        } catch (TransformerFactoryConfigurationError | TransformerException e) {
        return formattedXmlString;

you can test it by simple calling above method with your unformatted xml as input argument. I have created a small web app and have added the functionality of pretty printing xml there. You can see the relevant code (beautifyXml method)-
You can clone the webapp itself and see how it works for yourself. It all on github -

preety printing JSON

You can do similar stuff for Json too -

    public static String beautifyJson(String unformattedStringForm) {
        JsonParser parser = new JsonParser();
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        try {
            String jsonString = unformattedStringForm;
            JsonElement el = parser.parse(jsonString);
            return gson.toJson(el);
        catch(JsonSyntaxException e) {
        return null;

Again relevant code can be found in (beautifyJson method) -

Related Links

t> UA-39527780-1 back to top