How to pretty print XML from Java?

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

    Just another solution which works for us

    import java.io.StringWriter;
    import org.dom4j.DocumentHelper;
    import org.dom4j.io.OutputFormat;
    import org.dom4j.io.XMLWriter;
    
    **
     * Pretty Print XML String
     * 
     * @param inputXmlString
     * @return
     */
    public static String prettyPrintXml(String xml) {
    
        final StringWriter sw;
    
        try {
            final OutputFormat format = OutputFormat.createPrettyPrint();
            final org.dom4j.Document document = DocumentHelper.parseText(xml);
            sw = new StringWriter();
            final XMLWriter writer = new XMLWriter(sw, format);
            writer.write(document);
        }
        catch (Exception e) {
            throw new RuntimeException("Error pretty printing xml:\n" + xml, e);
        }
        return sw.toString();
    }
    

提交回复
热议问题