1
2
3
4
5
6
7
8
9
10
11 package org.mod4j.dslcommon.xml;
12
13 import java.io.File;
14 import java.io.FileOutputStream;
15 import java.io.IOException;
16 import java.io.Reader;
17
18 import org.jdom.Document;
19 import org.jdom.JDOMException;
20 import org.jdom.input.SAXBuilder;
21
22
23 import org.jdom.output.Format;
24 import org.jdom.output.XMLOutputter;
25
26
27
28
29
30
31
32 public class XmlUtil {
33
34
35
36
37
38
39
40
41
42 public static Document readXmlDocument(File file, boolean ignoreWhitespace) {
43 try {
44 SAXBuilder builder = null;
45 builder = new SAXBuilder();
46 builder.setIgnoringElementContentWhitespace(ignoreWhitespace);
47
48 Document doc = builder.build(file);
49 return doc;
50 } catch (Exception e) {
51 e.printStackTrace();
52 }
53 return null;
54 }
55
56
57
58
59
60
61
62
63
64
65 public static Document readXmlDocument(Reader reader, boolean ignoreWhitespace) throws JDOMException {
66 try {
67 SAXBuilder builder = null;
68 builder = new SAXBuilder();
69 builder.setIgnoringElementContentWhitespace(ignoreWhitespace);
70
71 Document doc = builder.build(reader);
72 return doc;
73 } catch (IOException e) {
74 e.printStackTrace();
75 }
76 return null;
77 }
78
79 public static void writeDocument(Document doc, FileOutputStream stream, boolean newLines, String indent) {
80 try {
81 XMLOutputter outputter = new XMLOutputter();
82 Format format = Format.getPrettyFormat();
83 if (indent != null) {
84 format.setIndent(indent);
85 }
86 outputter.setFormat(format);
87 outputter.output(doc, stream);
88 } catch (IOException exc) {
89 exc.printStackTrace();
90 }
91 }
92
93 public static void writeDocument(Document doc, String outfilename, boolean newLines, String indent) {
94 try {
95 FileOutputStream stream = new FileOutputStream(new File(outfilename));
96 writeDocument(doc, stream, newLines, indent);
97 stream.close();
98 } catch (IOException exc) {
99 exc.printStackTrace();
100 }
101 }
102
103 }