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 String fixProlog(String xml) {
49
50
52 if (xml != null) {
53 char[] charArray = xml.toCharArray();
54
55 for (int i = 0; i < charArray.length; i++) {
56 if (charArray[i] == '<') {
57 if (i != 0) {
58 xml = xml.substring(i, xml.length());
59 }
60
61 break;
62 }
63 }
64 }
65
66 return xml;
67 }
68
69 public static String fromCompactSafe(String xml) {
70 return StringUtil.replace(xml, "[$NEW_LINE$]", "\n");
71 }
72
73 public static String toCompactSafe(String xml) {
74 return StringUtil.replace(xml, "\n", "[$NEW_LINE$]");
75 }
76
77 public static String toString(String xml)
78 throws DocumentException, IOException {
79
80 return toString(xml, StringPool.TAB);
81 }
82
83 public static String toString(String xml, String indent)
84 throws DocumentException, IOException {
85
86 SAXReader reader = new SAXReader();
87
88 Document doc = reader.read(new StringReader(xml));
89
90 return toString(doc, indent);
91 }
92
93 public static String toString(Branch branch) throws IOException {
94 return toString(branch, StringPool.TAB);
95 }
96
97 public static String toString(Branch branch, String indent)
98 throws IOException {
99
100 return toString(branch, StringPool.TAB, false);
101 }
102
103 public static String toString(
104 Branch branch, String indent, boolean expandEmptyElements)
105 throws IOException {
106
107 ByteArrayMaker bam = new ByteArrayMaker();
108
109 OutputFormat format = OutputFormat.createPrettyPrint();
110
111 format.setExpandEmptyElements(expandEmptyElements);
112 format.setIndent(indent);
113 format.setLineSeparator("\n");
114
115 XMLWriter writer = new XMLWriter(bam, format);
116
117 writer.write(branch);
118
119 String content = bam.toString(StringPool.UTF8);
120
121
123
125 if (content.endsWith("\n\n")) {
126 content = content.substring(0, content.length() - 2);
127 }
128
129 if (content.endsWith("\n")) {
130 content = content.substring(0, content.length() - 1);
131 }
132
133 while (content.indexOf(" \n") != -1) {
134 content = StringUtil.replace(content, " \n", "\n");
135 }
136
137 return content;
138 }
139
140 }