KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ca > commons > cbutil > CBXMLFormatter


1 package com.ca.commons.cbutil;
2
3 import org.w3c.dom.*;
4
5 import java.io.*;
6
7 /**
8  * <p>Takes a DOM tree and prints it out
9  * as nicely formatted XML</p>
10  */

11 public class CBXMLFormatter
12 {
13
14     /**
15      * use four spaces as default
16      */

17     private String JavaDoc tab = " ";
18
19     /**
20      * Line feed to use... could use
21      * different one for mac but can't be bothered :-)
22      */

23     private String JavaDoc newLine = System.getProperty("line.separator");
24
25     /**
26      * reusable serializer for static methods
27      */

28     private static CBXMLFormatter printer;
29
30     /**
31      * reusable writer for static methods
32      */

33     private static Writer writer;
34
35     public static void print(Node element)
36     {
37         if (printer == null)
38             printer = new CBXMLFormatter();
39
40         if (writer == null)
41             writer = new OutputStreamWriter(System.out);
42
43         try
44         {
45             printer.serializeNode(element, writer, " ");
46             writer.flush();
47         }
48         catch (IOException e)
49         {
50             System.err.println("IO exception writing to stdout: " + e);
51         }
52     }
53
54     public static String JavaDoc dumpToString(Node element)
55     {
56         if (printer == null)
57             printer = new CBXMLFormatter();
58
59         if (writer == null)
60             writer = new OutputStreamWriter(System.out);
61
62         try
63         {
64             return printer.serializeNode(element, new StringBuffer JavaDoc(), " ").toString();
65         }
66         catch (IOException e)
67         {
68             System.err.println("IO exception writing to stdout: " + e);
69         }
70
71         return "<error/>";
72     }
73
74     /**
75      * empty constructor
76      */

77     public CBXMLFormatter()
78     {
79     }
80
81     /**
82      * <p> This sets the tab size to use. </p>
83      *
84      * @param tab the tab size as an example string (e.g. ' ').
85      */

86     public void setTab(String JavaDoc tab)
87     {
88         this.tab = tab;
89     }
90
91     /**
92      * <p> This sets the carriage return character(s) to use.
93      * (default is '\n')
94      * </p>
95      *
96      * @param newLine the CR to use.
97      */

98     public void setNewLine(String JavaDoc newLine)
99     {
100         this.newLine = newLine;
101     }
102
103     /**
104      * <p> This serializes the DOM and prints
105      * it to standard out.</p>
106      *
107      * @param domTree DOM tree to printXML.
108      */

109
110     public void printXML(Document domTree)
111             throws IOException
112     {
113
114         Writer writer = new OutputStreamWriter(System.out);
115         printXML(domTree, writer);
116     }
117
118     /**
119      * <p> This serializes the DOM and sends it
120      * to the suplied output stream</p>
121      *
122      * @param domTree DOM tree to printXML.
123      * @param out <code>OutputStream</code> to write to.
124      */

125
126     public void printXML(Document domTree, OutputStream out)
127             throws IOException
128     {
129
130         Writer writer = new OutputStreamWriter(out);
131         printXML(domTree, writer);
132     }
133
134     /**
135      * <p> This serializes a DOM tree and sends it to
136      * the provided writer.</p>
137      *
138      * @param domTree DOM tree to printXML.
139      * @param writer a Writer object to output to.
140      */

141
142     public void printXML(Document domTree, Writer writer)
143             throws IOException
144     {
145
146         // Start serialization recursion with no indenting
147
serializeNode(domTree, writer, "");
148         writer.flush();
149     }
150
151     /**
152      * <p> This will printXML the DOM subtree of
153      * the provided node. </p>
154      *
155      * @param node the document node to printXML.
156      * @param writer the output Writer to output text to.
157      * @param tabs size text is inset.
158      */

159     public void serializeNode(Node node, Writer writer,
160                               String JavaDoc tabs)
161             throws IOException
162     {
163         // Determine action based on node type
164
switch (node.getNodeType())
165         {
166             case Node.DOCUMENT_NODE:
167                 writer.write("<?xml version=\"1.0\"?>" + newLine);
168
169                 // recurse on each child
170
NodeList nodes = node.getChildNodes();
171                 if (nodes != null)
172                 {
173                     for (int nodeNo = 0; nodeNo < nodes.getLength(); nodeNo++)
174                     {
175                         serializeNode(nodes.item(nodeNo), writer, "");
176                     }
177                 }
178                 break;
179
180             case Node.ELEMENT_NODE:
181                 String JavaDoc name = node.getNodeName();
182                 writer.write(tabs + "<" + name);
183                 NamedNodeMap attributes = node.getAttributes();
184                 for (int i = 0; i < attributes.getLength(); i++)
185                 {
186                     Node current = attributes.item(i);
187                     writer.write(" " + current.getNodeName() + "=\"" + current.getNodeValue() + "\"");
188                 }
189                 writer.write(">");
190
191                 // recurse on each child
192
NodeList children = node.getChildNodes();
193                 if (children != null)
194                 {
195                     if ((children.item(0) != null) &&
196                             (children.item(0).getNodeType() ==
197                             Node.ELEMENT_NODE))
198                     {
199                         writer.write(newLine);
200                     }
201                     for (int i = 0; i < children.getLength(); i++)
202                     {
203                         serializeNode(children.item(i), writer, tabs + tab);
204                     }
205                     if ((children.item(0) != null)
206                             && (children.item(children.getLength() - 1).getNodeType() == Node.ELEMENT_NODE))
207                     {
208                         writer.write(tabs);
209                     }
210                 }
211
212                 writer.write("</" + name + ">");
213                 writer.write(newLine);
214                 break;
215
216             case Node.TEXT_NODE:
217                 writer.write(node.getNodeValue());
218                 break;
219
220             case Node.CDATA_SECTION_NODE:
221                 writer.write("<![CDATA[" + node.getNodeValue() + "]]>");
222                 break;
223
224             case Node.COMMENT_NODE:
225                 writer.write(tabs + "<!-- " + node.getNodeValue() + " -->");
226                 writer.write(newLine);
227                 break;
228
229             case Node.PROCESSING_INSTRUCTION_NODE:
230                 writer.write("<?" + node.getNodeName() + " " + node.getNodeValue() + "?>");
231                 writer.write(newLine);
232                 break;
233
234             case Node.ENTITY_REFERENCE_NODE:
235                 writer.write("&" + node.getNodeName() + ";");
236                 break;
237
238             case Node.DOCUMENT_TYPE_NODE:
239                 DocumentType docType = (DocumentType) node;
240                 writer.write("<!DOCTYPE " + docType.getName());
241                 if (docType.getPublicId() != null)
242                 {
243                     System.out.print(" PUBLIC \"" + docType.getPublicId() + "\" ");
244                 }
245                 else
246                 {
247                     writer.write(" SYSTEM ");
248                 }
249                 writer.write("\"" + docType.getSystemId() + "\">");
250                 writer.write(newLine);
251                 break;
252         }
253     }
254
255     /**
256      * <p> This will printXML the DOM subtree of
257      * the provided node. Formatting it for HTML. </p>
258      *
259      * @param node the document node to printXML.
260      * @param tabs size text is inset.
261      */

262     public StringBuffer JavaDoc serializeNode(Node node, StringBuffer JavaDoc buffy, String JavaDoc tabs)
263             throws IOException
264     {
265
266         // Determine action based on node type
267
switch (node.getNodeType())
268         {
269             case Node.DOCUMENT_NODE:
270                 buffy.append("<?xml version=\"1.0\"?>" + newLine);
271
272                 // recurse on each child
273
NodeList nodes = node.getChildNodes();
274                 if (nodes != null)
275                 {
276                     for (int nodeNo = 0; nodeNo < nodes.getLength(); nodeNo++)
277                     {
278                         serializeNode(nodes.item(nodeNo), buffy, "");
279                     }
280                 }
281                 break;
282
283             case Node.ELEMENT_NODE:
284                 String JavaDoc name = node.getNodeName();
285                 buffy.append(tabs + CBParse.toHTML("<" + name));
286                 NamedNodeMap attributes = node.getAttributes();
287                 for (int i = 0; i < attributes.getLength(); i++)
288                 {
289                     Node current = attributes.item(i);
290                     buffy.append(CBParse.toHTML(" " + current.getNodeName() + "=\"" + current.getNodeValue() + "\""));
291                 }
292                 buffy.append(CBParse.toHTML(">"));
293
294                 // recurse on each child
295
NodeList children = node.getChildNodes();
296                 if (children != null)
297                 {
298                     if ((children.item(0) != null) &&
299                             (children.item(0).getNodeType() ==
300                             Node.ELEMENT_NODE))
301                     {
302                         buffy.append(newLine);
303                     }
304                     for (int i = 0; i < children.getLength(); i++)
305                     {
306                         serializeNode(children.item(i), buffy, tabs + tab);
307                     }
308                     if ((children.item(0) != null)
309                             && (children.item(children.getLength() - 1).getNodeType() == Node.ELEMENT_NODE))
310                     {
311                         buffy.append(tabs);
312                     }
313                 }
314
315                 buffy.append(CBParse.toHTML("</" + name + ">"));
316                 buffy.append(newLine);
317                 break;
318
319             case Node.TEXT_NODE:
320                 buffy.append(CBParse.toHTML(node.getNodeValue()));
321                 break;
322
323             case Node.CDATA_SECTION_NODE:
324                 buffy.append(CBParse.toHTML("<![CDATA[" + node.getNodeValue() + "]]>"));
325                 break;
326
327             case Node.COMMENT_NODE:
328                 buffy.append(tabs + CBParse.toHTML("<!-- " + node.getNodeValue() + " -->"));
329                 buffy.append(newLine);
330                 break;
331
332             case Node.PROCESSING_INSTRUCTION_NODE:
333                 buffy.append(CBParse.toHTML("<?" + node.getNodeName() + " " + node.getNodeValue() + "?>"));
334                 buffy.append(newLine);
335                 break;
336
337             case Node.ENTITY_REFERENCE_NODE:
338                 buffy.append(CBParse.toHTML("&" + node.getNodeName() + ";"));
339                 break;
340
341             case Node.DOCUMENT_TYPE_NODE:
342                 DocumentType docType = (DocumentType) node;
343                 buffy.append(CBParse.toHTML("<!DOCTYPE " + docType.getName()));
344                 if (docType.getPublicId() != null)
345                 {
346                     System.out.print(" PUBLIC \"" + docType.getPublicId() + "\" ");
347                 }
348                 else
349                 {
350                     buffy.append(CBParse.toHTML(" SYSTEM "));
351                 }
352                 buffy.append(CBParse.toHTML("\"" + docType.getSystemId() + "\">"));
353                 buffy.append(newLine);
354                 break;
355         }
356
357         return buffy;
358     }
359 }
Popular Tags