How to pretty print XML from Java?

后端 未结 30 2932
慢半拍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条回答
  •  萌比男神i
    2020-11-22 02:48

    Here's a way of doing it using dom4j:

    Imports:

    import org.dom4j.Document;  
    import org.dom4j.DocumentHelper;  
    import org.dom4j.io.OutputFormat;  
    import org.dom4j.io.XMLWriter;
    

    Code:

    String xml = "";  
    Document doc = DocumentHelper.parseText(xml);  
    StringWriter sw = new StringWriter();  
    OutputFormat format = OutputFormat.createPrettyPrint();  
    XMLWriter xw = new XMLWriter(sw, format);  
    xw.write(doc);  
    String result = sw.toString();
    

提交回复
热议问题