How to pretty print XML from Java?

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

    Using jdom2 : http://www.jdom.org/

    import java.io.StringReader;
    import org.jdom2.input.SAXBuilder;
    import org.jdom2.output.Format;
    import org.jdom2.output.XMLOutputter;
    
    String prettyXml = new XMLOutputter(Format.getPrettyFormat()).
                             outputString(new SAXBuilder().build(new StringReader(uglyXml)));
    

提交回复
热议问题