How to pretty print XML from Java?

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

    Regarding comment that "you must first build a DOM tree": No, you need not and should not do that.

    Instead, create a StreamSource (new StreamSource(new StringReader(str)), and feed that to the identity transformer mentioned. That'll use SAX parser, and result will be much faster. Building an intermediate tree is pure overhead for this case. Otherwise the top-ranked answer is good.

提交回复
热议问题