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>
I saw one answer using
Scala
, so here is another one inGroovy
, just in case someone finds it interesting. The default indentation is 2 steps,XmlNodePrinter
constructor can be passed another value as well.Usage from Java if groovy jar is in classpath
Note: Results may vary depending on the Java version. Search for workarounds specific to your platform.
All above solutions didn't work for me, then I found this http://myshittycode.com/2014/02/10/java-properly-indenting-xml-string/
The clue is remove whitespaces with XPath
Now it's 2012 and Java can do more than it used to with XML, I'd like to add an alternative to my accepted answer. This has no dependencies outside of Java 6.
In case you do not need indentation that much but a few line breaks, it could be sufficient to simply regex...
The code is nice, not the result because of missing indentation.
(For solutions with indentation, see other answers.)
If you're sure that you have a valid XML, this one is simple, and avoids XML DOM trees. Maybe has some bugs, do comment if you see anything