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