KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > soap > util > xml > DOMWriter


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  *
5  * Copyright (c) 2000 The Apache Software Foundation. All rights
6  * reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  * notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  * notice, this list of conditions and the following disclaimer in
17  * the documentation and/or other materials provided with the
18  * distribution.
19  *
20  * 3. The end-user documentation included with the redistribution,
21  * if any, must include the following acknowledgment:
22  * "This product includes software developed by the
23  * Apache Software Foundation (http://www.apache.org/)."
24  * Alternately, this acknowledgment may appear in the software itself,
25  * if and wherever such third-party acknowledgments normally appear.
26  *
27  * 4. The names "SOAP" and "Apache Software Foundation" must
28  * not be used to endorse or promote products derived from this
29  * software without prior written permission. For written
30  * permission, please contact apache@apache.org.
31  *
32  * 5. Products derived from this software may not be called "Apache",
33  * nor may "Apache" appear in their name, without prior written
34  * permission of the Apache Software Foundation.
35  *
36  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This software consists of voluntary contributions made by many
51  * individuals on behalf of the Apache Software Foundation and was
52  * originally based on software copyright (c) 2000, International
53  * Business Machines, Inc., http://www.apache.org. For more
54  * information on the Apache Software Foundation, please see
55  * <http://www.apache.org/>.
56  */

57
58 package org.apache.soap.util.xml;
59
60 import java.io.*;
61 import org.w3c.dom.*;
62 import org.apache.soap.util.StringUtils;
63
64 /**
65  * This class is a utility to serialize a DOM node as XML. This code is
66  * derived from the sample of the same name distributed with XML4J_2_0_15.
67  * The following significant changes were made:
68  * comments and top-level PIs, now uses short-hand element syntax when an
69  * element is childless, now attempts to use the correct line-termination
70  * sequence. Also: removed the code related to canonical ordering, alternate
71  * encodings, and use as a stand-alone utility.
72  *
73  * @author Matthew J. Duftler (duftler@us.ibm.com)
74  */

75 public class DOMWriter
76 {
77   /**
78    * Return a string containing this node serialized as XML.
79    */

80   public static String JavaDoc nodeToString(Node node)
81   {
82     StringWriter sw = new StringWriter();
83
84     serializeAsXML(node, sw);
85
86     return sw.toString();
87   }
88
89   /**
90   * Serialize this node into the writer as XML.
91   */

92   public static void serializeAsXML(Node node, Writer writer)
93   {
94     print(node, new PrintWriter(writer));
95   }
96
97   private static void print(Node node, PrintWriter out)
98   {
99     if (node == null)
100     {
101       return;
102     }
103
104     boolean hasChildren = false;
105     int type = node.getNodeType();
106
107     switch (type)
108     {
109       case Node.DOCUMENT_NODE :
110       {
111         out.println("<?xml version=\"1.0\"?>");
112
113         NodeList children = node.getChildNodes();
114
115         if (children != null)
116         {
117           int numChildren = children.getLength();
118
119           for (int i = 0; i < numChildren; i++)
120           {
121             print(children.item(i), out);
122           }
123         }
124         break;
125       }
126
127       case Node.ELEMENT_NODE :
128       {
129         out.print('<' + node.getNodeName());
130
131         NamedNodeMap attrs = node.getAttributes();
132         int len = (attrs != null) ? attrs.getLength() : 0;
133
134         for (int i = 0; i < len; i++)
135         {
136           Attr attr = (Attr)attrs.item(i);
137
138           out.print(' ' + attr.getNodeName() +"=\"" +
139                     normalize(attr.getValue()) + '\"');
140         }
141
142         NodeList children = node.getChildNodes();
143
144         if (children != null)
145         {
146           int numChildren = children.getLength();
147
148           hasChildren = (numChildren > 0);
149
150           if (hasChildren)
151           {
152             out.print('>');
153           }
154
155           for (int i = 0; i < numChildren; i++)
156           {
157             print(children.item(i), out);
158           }
159         }
160         else
161         {
162           hasChildren = false;
163         }
164
165         if (!hasChildren)
166         {
167           out.print("/>");
168         }
169         break;
170       }
171
172       case Node.ENTITY_REFERENCE_NODE :
173       {
174         out.print('&');
175         out.print(node.getNodeName());
176         out.print(';');
177         break;
178       }
179
180       case Node.CDATA_SECTION_NODE :
181       {
182         out.print("<![CDATA[");
183         out.print(node.getNodeValue());
184         out.print("]]>");
185         break;
186       }
187
188       case Node.TEXT_NODE :
189       {
190         out.print(normalize(node.getNodeValue()));
191         break;
192       }
193
194       case Node.COMMENT_NODE :
195       {
196         out.print("<!--");
197         out.print(node.getNodeValue());
198         out.print("-->");
199         break;
200       }
201
202       case Node.PROCESSING_INSTRUCTION_NODE :
203       {
204         out.print("<?");
205         out.print(node.getNodeName());
206
207         String JavaDoc data = node.getNodeValue();
208
209         if (data != null && data.length() > 0)
210         {
211           out.print(' ');
212           out.print(data);
213         }
214
215         out.println("?>");
216         break;
217       }
218     }
219
220     if (type == Node.ELEMENT_NODE && hasChildren == true)
221     {
222       out.print("</");
223       out.print(node.getNodeName());
224       out.print('>');
225       hasChildren = false;
226     }
227   }
228
229   private static String JavaDoc normalize(String JavaDoc s)
230   {
231     StringBuffer JavaDoc str = new StringBuffer JavaDoc();
232     int len = (s != null) ? s.length() : 0;
233
234     for (int i = 0; i < len; i++)
235     {
236       char ch = s.charAt(i);
237
238       switch (ch)
239       {
240         case '<' :
241         {
242           str.append("&lt;");
243           break;
244         }
245         case '>' :
246         {
247           str.append("&gt;");
248           break;
249         }
250         case '&' :
251         {
252           str.append("&amp;");
253           break;
254         }
255         case '"' :
256         {
257           str.append("&quot;");
258           break;
259         }
260         case '\n' :
261         {
262           if (i > 0)
263           {
264             char lastChar = str.charAt(str.length() - 1);
265
266             if (lastChar != '\r')
267             {
268               str.append(StringUtils.lineSeparator);
269             }
270             else
271             {
272               str.append('\n');
273             }
274           }
275           else
276           {
277             str.append(StringUtils.lineSeparator);
278           }
279           break;
280         }
281         default :
282         {
283           str.append(ch);
284         }
285       }
286     }
287
288     return (str.toString());
289   }
290 }
291
Popular Tags