How to pretty print XML from Java?

后端 未结 30 2532
慢半拍i
慢半拍i 2020-11-22 01:55

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?



        
30条回答
  •  無奈伤痛
    2020-11-22 02:30

    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());
    

提交回复
热议问题