1 package zeus.util;
2
3 /***
4 * Format an XML String
5 */
6 public class XMLFormatter {
7
8 private static final String indent = " ";
9
10 /***
11 * Add formatting to an XML string
12 */
13 public static String formatXML(String xmlContent) {
14
15 String result = "";
16
17 try {
18
19 for(int indentLevel = 0, index = 0 ;
20 index < xmlContent.length() ;
21 index++) {
22
23
24 index = xmlContent.indexOf("<", index);
25
26 if(index < 0 || index >= xmlContent.length())
27 break;
28
29
30 String section =
31 xmlContent.substring(index, xmlContent.indexOf(">", index) + 1);
32
33 if(section.matches("<!--.*-->")) {
34
35 result = indent(result, indentLevel);
36 }
37 else if(section.matches("<!.*>")) {
38
39 result = indent(result, indentLevel);
40 }
41 else if(section.matches("<//?.*//?>")) {
42
43 result = indent(result, indentLevel);
44 }
45 else if(section.matches("<[//s]*[/////].*>")) {
46
47 result = indent(result, --indentLevel);
48 }
49 else if(section.matches("<.*[/////][//s]*>")) {
50
51 result = indent(result, indentLevel);
52 }
53 else {
54
55 result = indent(result, indentLevel++);
56 }
57
58 result += section + "\n";
59 }
60 }
61 catch(StringIndexOutOfBoundsException s) {
62 s.printStackTrace();
63 return "Invalid XML";
64 }
65
66 return result;
67 }
68
69 public static String indent(String text, int indentLevel) {
70
71 for( int count = indentLevel ; count > 0 ; count--)
72 text += indent;
73
74 return text;
75 }
76 }