How to pretty print XML from Java?

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

    This code below working perfectly

    import javax.xml.transform.OutputKeys;
    import javax.xml.transform.Source;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.stream.StreamResult;
    import javax.xml.transform.stream.StreamSource;
    
    String formattedXml1 = prettyFormat("aaa");
    
    public static String prettyFormat(String input) {
        return prettyFormat(input, "2");
    }
    
    public static String prettyFormat(String input, String indent) {
        Source xmlInput = new StreamSource(new StringReader(input));
        StringWriter stringWriter = new StringWriter();
        try {
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", indent);
            transformer.transform(xmlInput, new StreamResult(stringWriter));
    
            String pretty = stringWriter.toString();
            pretty = pretty.replace("\r\n", "\n");
            return pretty;              
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    

提交回复
热议问题