Java XML Formatter With Examples

eXtensive Markup Language (XML) is one of the popular medium for messaging and communication between different applications. Since XML is open source and provides control over data format via DTD and XSDs, it’s widely used across technologies.

Java XML Formatter

Few days back, I came across a situation where the third party API was returning Document object and XML message as String. So I wrote this simple XmlFormatter class to format the XML with proper indentation and convert Document object to XML String.

To use this class, you need Apache xercesImpl.jar that you can download from their website.

Output of the above class is a properly formatted XML String:

I hope you will find this utility class helpful in formatting XML in Java and converting XML to Document and vice versa.

Update

It’s been many years since I wrote this article, java has evolved a lot and we can format XML string easily using javax.xml.transform API.

The output will be the same as earlier, you should use this instead of adding a dependency on any third party API.

By admin

Leave a Reply

%d bloggers like this: