1 package org.kuali.ole.docstore.common;
2
3 import org.apache.commons.lang3.ArrayUtils;
4 import org.apache.commons.lang3.StringUtils;
5 import org.dom4j.DocumentHelper;
6 import org.dom4j.io.OutputFormat;
7 import org.dom4j.io.XMLWriter;
8
9 import java.io.StringWriter;
10
11
12
13
14 public class XMLFormatter {
15 public static String prettyPrint(final String xml) {
16 if (StringUtils.isBlank(xml)) {
17 throw new RuntimeException("xml was null or blank in prettyPrint()");
18 }
19
20 final StringWriter sw;
21
22 try {
23 final OutputFormat format = OutputFormat.createPrettyPrint();
24 final org.dom4j.Document document = DocumentHelper.parseText(xml);
25 sw = new StringWriter();
26 final XMLWriter writer = new XMLWriter(sw, format);
27 writer.write(document);
28 } catch (Exception e) {
29 throw new RuntimeException("Error pretty printing xml:\n" + xml, e);
30 }
31 String[] xmlArray = StringUtils.split(sw.toString(), '\n');
32 Object[] xmlContent = ArrayUtils.subarray(xmlArray, 1, xmlArray.length);
33 StringBuilder xmlStr = new StringBuilder();
34 for (Object object : xmlContent) {
35 xmlStr.append(object.toString());
36 xmlStr.append('\n');
37 }
38 return xmlStr.toString();
39 }
40 }