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