1 package org.kuali.ole.deliver.util;
2
3 import org.apache.xml.serialize.OutputFormat;
4 import org.apache.xml.serialize.XMLSerializer;
5 import org.w3c.dom.Document;
6 import org.xml.sax.InputSource;
7 import org.xml.sax.SAXException;
8
9 import javax.xml.parsers.DocumentBuilder;
10 import javax.xml.parsers.DocumentBuilderFactory;
11 import javax.xml.parsers.ParserConfigurationException;
12 import java.io.IOException;
13 import java.io.StringReader;
14 import java.io.StringWriter;
15 import java.io.Writer;
16
17
18
19
20 public class XMLFormatterUtil {
21
22 public static String formatContentForPretty(String content){
23 try {
24 final Document document = parseXmlFile(content);
25 OutputFormat format = new OutputFormat(document);
26 format.setLineWidth(65);
27 format.setIndenting(true);
28 format.setIndent(2);
29 Writer out = new StringWriter();
30 XMLSerializer serializer = new XMLSerializer(out, format);
31 serializer.serialize(document);
32 return out.toString();
33 } catch (IOException e) {
34 throw new RuntimeException(e);
35 }
36
37 }
38
39 public static Document parseXmlFile(String in) {
40 try {
41 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
42 DocumentBuilder db = dbf.newDocumentBuilder();
43 InputSource is = new InputSource(new StringReader(in));
44 return db.parse(is);
45 } catch (ParserConfigurationException e) {
46 throw new RuntimeException(e);
47 } catch (SAXException e) {
48 throw new RuntimeException(e);
49 } catch (IOException e) {
50 throw new RuntimeException(e);
51 }
52 }
53 }