Sunday, April 22, 2012

How to format an XML String in java

Generally we get XMLs as string in java and that is highly unreadable and unformatted.

How do I format it ??

I am just presenting one of the many ways to do that.

Thanks to http://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java

You would need to import these:

import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

Pretty straight forward function is available:

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();
            // This statement works with JDK 6
            transformerFactory.setAttribute("indent-number", indent);
            
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.transform(xmlInput, xmlOutput);
            return xmlOutput.getWriter().toString();
        }
        catch (Throwable e)
        {
            // You'll come here if you are using JDK 1.5
            // you are getting an the following exeption
            // java.lang.IllegalArgumentException: Not supported: indent-number
            // Use this code (Set the output property in transformer.
            try
            {
                Source xmlInput = new StreamSource(new StringReader(input));
                StringWriter stringWriter = new StringWriter();
                StreamResult xmlOutput = new StreamResult(stringWriter);
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent));
                transformer.transform(xmlInput, xmlOutput);
                return xmlOutput.getWriter().toString();
            }
            catch(Throwable t)
            {
                return input;
            }
        }
    }

    public static String prettyFormat(String input) {
        return prettyFormat(input, 2);
    }

16 comments:

  1. This helped a lot. Exactly what I needed. Thanks for the useful article!

    ReplyDelete
    Replies
    1. Your welcome Eric.... That helped me a lot, so i had put it on my blog. :)

      ( Author of this blog )

      Delete
  2. Thanks a lot, it worked for me as in my case the parsing method of documentBuilder require a formatted xml string.

    ReplyDelete
  3. wow just wow. you and this is awesome. thanks!

    ReplyDelete
  4. the code in catch works but in the try even with jdk7 I get the exception.

    ReplyDelete
  5. Very helpful code. Thank you.

    ReplyDelete