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$]", StringPool.NEW_LINE);
68 }
69
70 public static String toCompactSafe(String xml) {
71 return StringUtil.replace(
72 xml,
73 new String[] {
74 StringPool.RETURN_NEW_LINE,
75 StringPool.NEW_LINE,
76 StringPool.RETURN
77 },
78 new String[] {
79 "[$NEW_LINE$]",
80 "[$NEW_LINE$]",
81 "[$NEW_LINE$]"
82 });
83 }
84
85 public static String toString(String xml)
86 throws DocumentException, IOException {
87
88 return toString(xml, StringPool.TAB);
89 }
90
91 public static String toString(String xml, String indent)
92 throws DocumentException, IOException {
93
94 SAXReader reader = new SAXReader();
95
96 Document doc = reader.read(new StringReader(xml));
97
98 return toString(doc, indent);
99 }
100
101 public static String toString(Branch branch) throws IOException {
102 return toString(branch, StringPool.TAB);
103 }
104
105 public static String toString(Branch branch, String indent)
106 throws IOException {
107
108 return toString(branch, StringPool.TAB, false);
109 }
110
111 public static String toString(
112 Branch branch, String indent, boolean expandEmptyElements)
113 throws IOException {
114
115 ByteArrayMaker bam = new ByteArrayMaker();
116
117 OutputFormat format = OutputFormat.createPrettyPrint();
118
119 format.setExpandEmptyElements(expandEmptyElements);
120 format.setIndent(indent);
121 format.setLineSeparator("\n");
122
123 XMLWriter writer = new XMLWriter(bam, format);
124
125 writer.write(branch);
126
127 String content = bam.toString(StringPool.UTF8);
128
129
131
133 if (content.endsWith("\n\n")) {
134 content = content.substring(0, content.length() - 2);
135 }
136
137 if (content.endsWith("\n")) {
138 content = content.substring(0, content.length() - 1);
139 }
140
141 while (content.indexOf(" \n") != -1) {
142 content = StringUtil.replace(content, " \n", "\n");
143 }
144
145 return content;
146 }
147
148 }