How to pretty print XML from Java?

后端 未结 30 2486
慢半拍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:51

    Using scala:

    import xml._
    val xml = XML.loadString("hello")
    val formatted = new PrettyPrinter(150, 2).format(xml)
    println(formatted)
    

    You can do this in Java too, if you depend on the scala-library.jar. It looks like this:

    import scala.xml.*;
    
    public class FormatXML {
        public static void main(String[] args) {
            String unformattedXml = "hello";
            PrettyPrinter pp = new PrettyPrinter(150, 3);
            String formatted = pp.format(XML.loadString(unformattedXml), TopScope$.MODULE$);
            System.out.println(formatted);
        }
    }
    

    The PrettyPrinter object is constructed with two ints, the first being max line length and the second being the indentation step.

提交回复
热议问题