1
22
23 package com.liferay.util.xml;
24
25 import com.liferay.portal.kernel.util.ByteArrayMaker;
26 import com.liferay.portal.kernel.util.StringUtil;
27
28 import java.io.IOException;
29 import java.io.StringReader;
30
31 import org.dom4j.Branch;
32 import org.dom4j.Document;
33 import org.dom4j.DocumentException;
34 import org.dom4j.io.OutputFormat;
35 import org.dom4j.io.SAXReader;
36 import org.dom4j.io.XMLWriter;
37
38
45 public class XMLFormatter {
46
47 public static final String ENCODING = "UTF-8";
48
49 public static final String INDENT = "\t";
50
51 public static String fixProlog(String xml) {
52
53
55 if (xml != null) {
56 char[] charArray = xml.toCharArray();
57
58 for (int i = 0; i < charArray.length; i++) {
59 if (charArray[i] == '<') {
60 if (i != 0) {
61 xml = xml.substring(i, xml.length());
62 }
63
64 break;
65 }
66 }
67 }
68
69 return xml;
70 }
71
72 public static String fromCompactSafe(String xml) {
73 return StringUtil.replace(xml, "[$NEW_LINE$]", "\n");
74 }
75
76 public static String toCompactSafe(String xml) {
77 return StringUtil.replace(xml, "\n", "[$NEW_LINE$]");
78 }
79
80 public static String toString(String xml)
81 throws DocumentException, IOException {
82
83 return toString(xml, INDENT);
84 }
85
86 public static String toString(String xml, String indent)
87 throws DocumentException, IOException {
88
89 SAXReader reader = new SAXReader();
90
91 Document doc = reader.read(new StringReader(xml));
92
93 return toString(doc, indent);
94 }
95
96 public static String toString(Branch branch) throws IOException {
97 return toString(branch, INDENT);
98 }
99
100 public static String toString(Branch branch, String indent)
101 throws IOException {
102
103 return toString(branch, INDENT, false);
104 }
105
106 public static String toString(
107 Branch branch, String indent, boolean expandEmptyElements)
108 throws IOException {
109
110 ByteArrayMaker bam = new ByteArrayMaker();
111
112 OutputFormat format = OutputFormat.createPrettyPrint();
113
114 format.setExpandEmptyElements(expandEmptyElements);
115 format.setIndent(indent);
116 format.setLineSeparator("\n");
117
118 XMLWriter writer = new XMLWriter(bam, format);
119
120 writer.write(branch);
121
122 String content = bam.toString(ENCODING);
123
124
128
129 int x = content.indexOf("<!DOCTYPE");
130
131 if (x != -1) {
132 x = content.indexOf(">", x) + 1;
133
134 content = content.substring(0, x) + "\n" +
135 content.substring(x, content.length());
136 }
137
138 content = StringUtil.replace(content, "\n\n\n", "\n\n");
139
140 if (content.endsWith("\n\n")) {
141 content = content.substring(0, content.length() - 2);
142 }
143
144 if (content.endsWith("\n")) {
145 content = content.substring(0, content.length() - 1);
146 }
147
148 while (content.indexOf(" \n") != -1) {
149 content = StringUtil.replace(content, " \n", "\n");
150 }
151
152 return content;
153 }
154
155 }