View Javadoc

1   package de.matthias_burbach.deputy.core.util;
2   
3   import java.io.FileOutputStream;
4   import java.io.InputStream;
5   
6   import org.jdom.Document;
7   import org.jdom.input.SAXBuilder;
8   import org.jdom.output.Format;
9   import org.jdom.output.XMLOutputter;
10  
11  /***
12   * @author Matthias Burbach
13   */
14  public final class XmlUtils {
15      /***
16       * Private default constructor to enforce static usage of this utility
17       * class.
18       */
19      private XmlUtils() {
20          //empty
21      }
22  
23      /***
24       * @param is The input stream to load the document from.
25       * @return The document loaded.
26       * @throws Exception if anything goes unexpectedly wrong
27       */
28      public static Document loadXmlDocument(
29              final InputStream is) throws Exception {
30          SAXBuilder builder = new SAXBuilder();
31          Document document = builder.build(is);
32          return document;
33      }
34  
35      /***
36       * @param url The URL to load the document from.
37       * @return The document loaded.
38       * @throws Exception if anything goes unexpectedly wrong
39       */
40      public static Document loadXmlDocument(final String url) throws Exception {
41          SAXBuilder builder = new SAXBuilder();
42          Document document = builder.build(url);
43          return document;
44      }
45  
46      /***
47       * @param pathAndFile The path and file name to save the document under.
48       * @param document The document to save.
49       * @throws Exception if anything goes unexpectedly wrong
50       */
51      public static void saveXmlDocument(
52                  final String pathAndFile,
53                  final Document document)
54                  throws Exception {
55          FileOutputStream fos = null;
56          try {
57              fos = new FileOutputStream(pathAndFile);
58              XMLOutputter outputter = new XMLOutputter();
59              Format format = Format.getPrettyFormat();
60              format.setEncoding("ISO-8859-1");
61              format.setIndent("    ");
62              outputter.setFormat(format);
63              outputter.output(document, fos);
64          } finally {
65              if (fos != null) {
66                  try {
67                      fos.close();
68                  } catch (Exception e) {
69                      e.printStackTrace();
70                  }
71              }
72          }
73      }
74  }