How to pretty print XML from Java?

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

    If you're sure that you have a valid XML, this one is simple, and avoids XML DOM trees. Maybe has some bugs, do comment if you see anything

    public String prettyPrint(String xml) {
                if (xml == null || xml.trim().length() == 0) return "";
    
                int stack = 0;
                StringBuilder pretty = new StringBuilder();
                String[] rows = xml.trim().replaceAll(">", ">\n").replaceAll("<", "\n<").split("\n");
    
                for (int i = 0; i < rows.length; i++) {
                        if (rows[i] == null || rows[i].trim().length() == 0) continue;
    
                        String row = rows[i].trim();
                        if (row.startsWith("

提交回复
热议问题