I have a Java String that contains XML, with no line feeds or indentations. I would like to turn it into a String with nicely formatted XML. How do I do this?
String unformattedXml = "<tag><nested>hello</nested></tag>";
String formattedXml = new [UnknownClass]().format(unformattedXml);
Note: My input is a String. My output is a String.
(Basic) mock result:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<tag>
<nested>hello</nested>
</tag>
</root>
Here's an answer to my own question. I combined the answers from the various results to write a class that pretty prints XML.
No guarantees on how it responds with invalid XML or large documents.
Here's a way of doing it using dom4j:
Imports:
Code:
I had the same problem and I'm having great success with JTidy (http://jtidy.sourceforge.net/index.html)
Example:
The solutions I have found here for Java 1.6+ do not reformat the code if it is already formatted. The one that worked for me (and re-formatted already formatted code) was the following.
It is a good tool to use in your unit tests for full-string xml comparison.
Just for future reference, here's a solution that worked for me (thanks to a comment that @George Hawkins posted in one of the answers):
Kevin Hakanson said: "However, if you know your XML string is valid, and you don't want to incur the memory overhead of parsing a string into a DOM, then running a transform over the DOM to get a string back - you could just do some old fashioned character by character parsing. Insert a newline and spaces after every characters, keep and indent counter (to determine the number of spaces) that you increment for every <...> and decrement for every you see."
Agreed. Such an approach is much faster and has far fewer dependencies.
Example solution: