1 package org.apache.archiva.xml;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import org.w3c.dom.Document;
23
24 import javax.xml.transform.OutputKeys;
25 import javax.xml.transform.Transformer;
26 import javax.xml.transform.TransformerException;
27 import javax.xml.transform.TransformerFactory;
28 import javax.xml.transform.dom.DOMSource;
29 import javax.xml.transform.stream.StreamResult;
30 import java.io.IOException;
31 import java.io.Writer;
32
33
34
35
36 public class XMLWriter {
37
38
39
40
41
42
43
44 public static void write(Document doc, Writer writer)
45 throws XMLException {
46 write(doc, writer, false);
47 }
48
49
50
51
52
53
54
55
56
57 public static void write(Document doc, Writer writer, boolean close)
58 throws XMLException {
59
60 try {
61 TransformerFactory transformerFactory = TransformerFactory.newInstance();
62 Transformer transformer = transformerFactory.newTransformer();
63 transformer.setOutputProperty(OutputKeys.INDENT, "yes");
64 try {
65 transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
66 } catch (IllegalArgumentException ex) {
67
68 }
69
70 writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
71 StreamResult result = new StreamResult(writer);
72 transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
73 DOMSource source = new DOMSource(doc);
74 transformer.transform(source, result);
75
76
77 } catch (TransformerException e) {
78 throw new XMLException("Could not create the xml transformer: " + e.getMessage(), e);
79 } catch (IOException e) {
80 throw new XMLException("Could not write to xml output: " + e.getMessage(), e);
81 } finally {
82 if (writer!=null) {
83 if (close) {
84 try {
85 writer.flush();
86 } catch (IOException e) {
87
88 }
89 try {
90 writer.close();
91 } catch (IOException e) {
92
93 }
94 }
95 }
96 }
97 }
98 }