KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > axis > utils > DOM2Writer


1 /*
2  * Copyright 2001-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.apache.axis.utils;
18
19 import org.w3c.dom.Attr JavaDoc;
20 import org.w3c.dom.Element JavaDoc;
21 import org.w3c.dom.NamedNodeMap JavaDoc;
22 import org.w3c.dom.Node JavaDoc;
23 import org.w3c.dom.NodeList JavaDoc;
24 import org.apache.axis.Constants;
25
26 import java.io.PrintWriter JavaDoc;
27 import java.io.StringWriter JavaDoc;
28 import java.io.Writer JavaDoc;
29
30
31 /**
32  * This class is a utility to serialize a DOM node as XML. This class
33  * uses the <code>DOM Level 2</code> APIs.
34  * The main difference between this class and DOMWriter is that this class
35  * generates and prints out namespace declarations.
36  *
37  * @author Matthew J. Duftler (duftler@us.ibm.com)
38  * @author Joseph Kesselman
39  */

40 public class DOM2Writer
41 {
42     /**
43      * Return a string containing this node serialized as XML.
44      */

45     public static String JavaDoc nodeToString(Node JavaDoc node, boolean omitXMLDecl)
46     {
47         StringWriter JavaDoc sw = new StringWriter JavaDoc();
48
49         serializeAsXML(node, sw, omitXMLDecl);
50
51         return sw.toString();
52     }
53
54     /**
55      * Serialize this node into the writer as XML.
56      */

57     public static void serializeAsXML(Node JavaDoc node, Writer JavaDoc writer,
58                                       boolean omitXMLDecl)
59     {
60         serializeAsXML(node, writer, omitXMLDecl, false);
61     }
62
63     /**
64      * Serialize this node into the writer as XML.
65      */

66     public static void serializeAsXML(Node JavaDoc node, Writer JavaDoc writer,
67                                       boolean omitXMLDecl,
68                                       boolean pretty)
69     {
70         PrintWriter JavaDoc out = new PrintWriter JavaDoc(writer);
71         if (!omitXMLDecl) {
72             out.print("<?xml version=\"1.0\" encoding=\"");
73             out.print(XMLUtils.getEncoding());
74             out.println("\"?>");
75         }
76         NSStack namespaceStack = new NSStack();
77         print(node, namespaceStack, node, out, pretty, 0);
78         out.flush();
79     }
80
81     private static void print(Node JavaDoc node, NSStack namespaceStack,
82                               Node JavaDoc startnode,
83                               PrintWriter JavaDoc out, boolean pretty,
84                               int indent)
85     {
86         if (node == null)
87         {
88             return;
89         }
90
91         boolean hasChildren = false;
92         int type = node.getNodeType();
93
94         switch (type)
95         {
96         case Node.DOCUMENT_NODE :
97             {
98                 NodeList JavaDoc children = node.getChildNodes();
99
100                 if (children != null)
101                 {
102                     int numChildren = children.getLength();
103
104                     for (int i = 0; i < numChildren; i++)
105                     {
106                         print(children.item(i), namespaceStack, startnode, out,
107                               pretty, indent);
108                     }
109                 }
110                 break;
111             }
112
113         case Node.ELEMENT_NODE :
114             {
115                 namespaceStack.push();
116
117                 if (pretty) {
118                     for (int i = 0; i < indent; i++)
119                         out.print(' ');
120                 }
121
122                 out.print('<' + node.getNodeName());
123
124                 String JavaDoc elPrefix = node.getPrefix();
125                 String JavaDoc elNamespaceURI = node.getNamespaceURI();
126
127                 if (elPrefix != null &&
128                         elNamespaceURI != null &&
129                         elPrefix.length() > 0)
130                 {
131                     boolean prefixIsDeclared = false;
132
133                     try
134                     {
135                         String JavaDoc namespaceURI = namespaceStack.getNamespaceURI(elPrefix);
136
137                         if (elNamespaceURI.equals(namespaceURI))
138                         {
139                             prefixIsDeclared = true;
140                         }
141                     }
142                     catch (IllegalArgumentException JavaDoc e)
143                     {
144                     }
145
146                     if (!prefixIsDeclared)
147                     {
148                         printNamespaceDecl(node, namespaceStack, startnode, out);
149                     }
150                 }
151
152                 NamedNodeMap JavaDoc attrs = node.getAttributes();
153                 int len = (attrs != null) ? attrs.getLength() : 0;
154
155                 for (int i = 0; i < len; i++)
156                 {
157                     Attr JavaDoc attr = (Attr JavaDoc)attrs.item(i);
158
159                     out.print(' ' + attr.getNodeName() +"=\"" +
160                               normalize(attr.getValue()) + '\"');
161
162                     String JavaDoc attrPrefix = attr.getPrefix();
163                     String JavaDoc attrNamespaceURI = attr.getNamespaceURI();
164
165                     if (attrPrefix != null &&
166                             attrNamespaceURI != null &&
167                             attrPrefix.length() > 0)
168                     {
169                         boolean prefixIsDeclared = false;
170
171                         try
172                         {
173                             String JavaDoc namespaceURI = namespaceStack.getNamespaceURI(attrPrefix);
174
175                             if (attrNamespaceURI.equals(namespaceURI))
176                             {
177                                 prefixIsDeclared = true;
178                             }
179                         }
180                         catch (IllegalArgumentException JavaDoc e)
181                         {
182                         }
183
184                         if (!prefixIsDeclared)
185                         {
186                             printNamespaceDecl(attr, namespaceStack, startnode, out);
187                         }
188                     }
189                 }
190
191                 NodeList JavaDoc children = node.getChildNodes();
192
193                 if (children != null)
194                 {
195                     int numChildren = children.getLength();
196
197                     hasChildren = (numChildren > 0);
198
199                     if (hasChildren)
200                     {
201                         out.print('>');
202                         if (pretty)
203                             out.print(JavaUtils.LS);
204                     }
205
206                     for (int i = 0; i < numChildren; i++)
207                     {
208                         print(children.item(i), namespaceStack, startnode, out, pretty,
209                               indent + 1);
210                     }
211                 }
212                 else
213                 {
214                     hasChildren = false;
215                 }
216
217                 if (!hasChildren)
218                 {
219                     out.print("/>");
220                     if (pretty)
221                         out.print(JavaUtils.LS);
222                 }
223
224                 namespaceStack.pop();
225                 break;
226             }
227
228         case Node.ENTITY_REFERENCE_NODE :
229             {
230                 out.print('&');
231                 out.print(node.getNodeName());
232                 out.print(';');
233                 break;
234             }
235
236         case Node.CDATA_SECTION_NODE :
237             {
238                 out.print("<![CDATA[");
239                 out.print(node.getNodeValue());
240                 out.print("]]>");
241                 break;
242             }
243
244         case Node.TEXT_NODE :
245             {
246                 out.print(normalize(node.getNodeValue()));
247                 break;
248             }
249
250         case Node.COMMENT_NODE :
251             {
252                 out.print("<!--");
253                 out.print(node.getNodeValue());
254                 out.print("-->");
255                 if (pretty)
256                     out.print(JavaUtils.LS);
257                 break;
258             }
259
260         case Node.PROCESSING_INSTRUCTION_NODE :
261             {
262                 out.print("<?");
263                 out.print(node.getNodeName());
264
265                 String JavaDoc data = node.getNodeValue();
266
267                 if (data != null && data.length() > 0)
268                 {
269                     out.print(' ');
270                     out.print(data);
271                 }
272
273                 out.println("?>");
274                 if (pretty)
275                     out.print(JavaUtils.LS);
276                 break;
277             }
278         }
279
280         if (type == Node.ELEMENT_NODE && hasChildren == true)
281         {
282             if (pretty) {
283                 for (int i = 0; i < indent; i++)
284                     out.print(' ');
285             }
286             out.print("</");
287             out.print(node.getNodeName());
288             out.print('>');
289             if (pretty)
290                 out.print(JavaUtils.LS);
291             hasChildren = false;
292         }
293     }
294
295     private static void printNamespaceDecl(Node JavaDoc node,
296                                            NSStack namespaceStack,
297                                            Node JavaDoc startnode,
298                                            PrintWriter JavaDoc out)
299     {
300         switch (node.getNodeType())
301         {
302         case Node.ATTRIBUTE_NODE :
303             {
304                 printNamespaceDecl(((Attr JavaDoc)node).getOwnerElement(), node,
305                                    namespaceStack, startnode, out);
306                 break;
307             }
308
309         case Node.ELEMENT_NODE :
310             {
311                 printNamespaceDecl((Element JavaDoc)node, node, namespaceStack, startnode, out);
312                 break;
313             }
314         }
315     }
316
317     private static void printNamespaceDecl(Element JavaDoc owner, Node JavaDoc node,
318                                            NSStack namespaceStack,
319                                            Node JavaDoc startnode,
320                                            PrintWriter JavaDoc out)
321     {
322         String JavaDoc namespaceURI = node.getNamespaceURI();
323         String JavaDoc prefix = node.getPrefix();
324
325         if (!(namespaceURI.equals(Constants.NS_URI_XMLNS) && prefix.equals("xmlns")) &&
326             !(namespaceURI.equals(Constants.NS_URI_XML) && prefix.equals("xml")))
327         {
328             if (XMLUtils.getNamespace(prefix, owner, startnode) == null)
329             {
330                 out.print(" xmlns:" + prefix + "=\"" + namespaceURI + '\"');
331             }
332         }
333         else
334         {
335             prefix = node.getLocalName();
336             namespaceURI = node.getNodeValue();
337         }
338
339         namespaceStack.add(namespaceURI, prefix);
340     }
341
342     public static String JavaDoc normalize(String JavaDoc s)
343     {
344         return XMLUtils.xmlEncodeString(s);
345     }
346 }
347
Popular Tags