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've pretty printed in the past using the org.dom4j.io.OutputFormat.createPrettyPrint() method
Using scala:
You can do this in Java too, if you depend on the scala-library.jar. It looks like this:
The
PrettyPrinter
object is constructed with two ints, the first being max line length and the second being the indentation step.This code below working perfectly
I mix all of them and writing one small program. It is reading from the xml file and printing out. Just Instead of xzy give your file path.
Using jdom2 : http://www.jdom.org/
For those searching for a quick and dirty solution - which doesn't need the XML to be 100% valid. e.g. in case of REST / SOAP logging (you never know what the others send ;-))
I found and advanced a code snipped I found online which I think is still missing here as a valid possible approach:
here is the output: