Last Updated:

Formatting XML or Pretty Print XML in Java


XML is one of the most popular ways to exchange data between different applications. Different messages and data can be transmitted in different ways, for example, as a string (a String object). This happened to me when a line of xml code came to the input without formatting and indentation. To deal with this, I wrote a special utility class. We'll break it down today.

In the last article, we learned how to convert a string to a Document and create a String from a Document. Now let's look at how to format the xml received in a string using the example below:

Pay attention to the following features of the program:

  • In the method, we can specify the value of the indentation.toPrettyXmlString()indent
  • We also used the XPath expression to remove spaces in the original string.
  • We used the capabilities of the class to define formatting options. For example, by passing a value to a parameter, you specified that you want to remove the XML declaration in the passed object.


Now let's run our utility class and look at the output in the console:

That's the beautiful and readable look of the converted string. In order to see the power and convenience of the above method of doing Pretty Print XML in Java, try passing a large unformatted string with XML markup to the input.