How to pretty print XML from Java?

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

    I had the same problem and I'm having great success with JTidy (http://jtidy.sourceforge.net/index.html)

    Example:

    Tidy t = new Tidy();
    t.setIndentContent(true);
    Document d = t.parseDOM(
        new ByteArrayInputStream("HTML goes here", null);
    
    OutputStream out = new ByteArrayOutputStream();
    t.pprint(d, out);
    String html = out.toString();
    

提交回复
热议问题