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?
I saw one answer using Scala
, so here is another one in Groovy
, just in case someone finds it interesting. The default indentation is 2 steps, XmlNodePrinter
constructor can be passed another value as well.
def xml = "hello "
def stringWriter = new StringWriter()
def node = new XmlParser().parseText(xml);
new XmlNodePrinter(new PrintWriter(stringWriter)).print(node)
println stringWriter.toString()
Usage from Java if groovy jar is in classpath
String xml = "hello ";
StringWriter stringWriter = new StringWriter();
Node node = new XmlParser().parseText(xml);
new XmlNodePrinter(new PrintWriter(stringWriter)).print(node);
System.out.println(stringWriter.toString());