KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > infoglue > cms > util > XMLHelper


1 /* ===============================================================================
2  *
3  * Part of the InfoGlue Content Management Platform (www.infoglue.org)
4  *
5  * ===============================================================================
6  *
7  * Copyright (C)
8  *
9  * This program is free software; you can redistribute it and/or modify it under
10  * the terms of the GNU General Public License version 2, as published by the
11  * Free Software Foundation. See the file LICENSE.html for more information.
12  *
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along with
18  * this program; if not, write to the Free Software Foundation, Inc. / 59 Temple
19  * Place, Suite 330 / Boston, MA 02111-1307 / USA.
20  *
21  * ===============================================================================
22  */

23
24 package org.infoglue.cms.util;
25
26 import java.io.BufferedInputStream JavaDoc;
27 import java.io.ByteArrayInputStream JavaDoc;
28 import java.io.File JavaDoc;
29 import java.io.FileReader JavaDoc;
30 import java.io.IOException JavaDoc;
31
32 import org.apache.xerces.parsers.DOMParser;
33 import org.w3c.dom.Document JavaDoc;
34 import org.w3c.dom.NamedNodeMap JavaDoc;
35 import org.w3c.dom.Node JavaDoc;
36 import org.w3c.dom.NodeList JavaDoc;
37 import org.xml.sax.InputSource JavaDoc;
38 import org.xml.sax.SAXException JavaDoc;
39  
40 /**
41  * This class is an utility class meant to be filled with reusable snippets of code concerning handling of XML
42  * in different shapes. No application specific code can be put here!!!
43  *
44  * @author Mattias Bogeblad
45  */

46  
47 public class XMLHelper
48 {
49     
50     /**
51      * Serializes the DOM-tree to a stringBuffer. Recursive method!
52      *
53      * @param node Node to start examining the tree from.
54      * @param writeString The StringBuffer you want to fill with xml.
55      * @return The StringBuffer containing the xml.
56      *
57      * @since 2002-12-12
58      * @author Mattias Bogeblad
59      */

60     
61     public static StringBuffer JavaDoc serializeDom(Node JavaDoc node, StringBuffer JavaDoc writeString)
62     {
63         int type = node.getNodeType();
64         try
65         {
66             switch (type)
67             {
68                 // print the document element
69
case Node.DOCUMENT_NODE:
70                 {
71                     writeString.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
72                     writeString = serializeDom(((Document JavaDoc)node).getDocumentElement(), writeString);
73                     break;
74                 }
75                 // print element with attributes
76
case Node.ELEMENT_NODE:
77                 {
78                     writeString.append("<");
79                     writeString.append(node.getNodeName());
80                     NamedNodeMap JavaDoc attrs = node.getAttributes();
81                     for (int i = 0; i < attrs.getLength(); i++)
82                     {
83                         Node JavaDoc attr = attrs.item(i);
84                         String JavaDoc outString = " " + attr.getNodeName() + "=\"" + replaceSpecialCharacters(attr.getNodeValue()) + "\"";
85                         writeString.append(outString);
86                     }
87                     writeString.append(">");
88                     NodeList JavaDoc children = node.getChildNodes();
89                     if (children != null)
90                     {
91                         int len = children.getLength();
92                         for (int i = 0; i < len; i++)
93                         writeString = serializeDom(children.item(i), writeString);
94                     }
95                     break;
96             }
97             // handle entity reference nodes
98
case Node.ENTITY_REFERENCE_NODE:
99             {
100                 String JavaDoc outString = "&" + node.getNodeName() + ";";
101                 writeString.append(outString);
102                 break;
103             }
104             // print cdata sections
105
case Node.CDATA_SECTION_NODE:
106             {
107                 String JavaDoc outString = "<![CDATA[" + node.getNodeValue() + "]]>";
108                 writeString.append(outString);
109                 break;
110             }
111             // print text
112
case Node.TEXT_NODE:
113             {
114                 writeString.append(replaceSpecialCharacters(node.getNodeValue()));
115                 break;
116             }
117             // print processing instruction
118
case Node.PROCESSING_INSTRUCTION_NODE:
119             {
120                 String JavaDoc data = node.getNodeValue();
121                 String JavaDoc outString = "<?" + node.getNodeName() + " " + data + "?>";
122                 writeString.append(outString);
123                 break;
124             }
125             }
126             if (type == Node.ELEMENT_NODE)
127             {
128                 String JavaDoc outString = "</" + node.getNodeName() + ">";
129                 writeString.append(outString);
130             }
131         }
132         catch (Exception JavaDoc e)
133         {
134
135         }
136         return writeString;
137     }
138
139
140     /**
141      * This method replaces special character with their xml-counterpart.
142      */

143     
144     public static String JavaDoc replaceSpecialCharacters(String JavaDoc value)
145     {
146         if(value == null)
147             return "";
148         
149             
150         StringBuffer JavaDoc newValue = new StringBuffer JavaDoc();
151         for (int i = 0; i < value.length(); i++)
152         {
153             char c = value.charAt(i);
154             if (c == '&')
155             {
156                 newValue.append("&amp;");
157             }
158             else if (c == '<')
159             {
160                 newValue.append("&lt;");
161             }
162             else if (c == '>')
163             {
164                 newValue.append("&gt;");
165             }
166             else if (c == '\'')
167             {
168                 newValue.append("&apos;");
169             }
170             else if (c == '\"')
171             {
172                 newValue.append("&quot;");
173             }
174             else
175             {
176                 if(isLegalCharacter((int)c))
177                     newValue.append(c);
178             }
179         }
180         return newValue.toString();
181     }
182     
183     
184     private static boolean isLegalCharacter(int ch)
185     {
186         return ch == 0x9 || ch == 0xA || ch == 0xD || (ch >= 0x20 && ch <= 0xFFFD) || (ch >= 0x1000 && ch <= 0x7FFFFFFF);
187
188     }
189     
190     /**
191      * This method fetches the document-root(DOM) from a xml-document located on disc specified
192      * by user argument.
193      *
194      * @since 2002-12-16
195      * @author Mattias Bogeblad
196      */

197       
198     public static Document JavaDoc readDocumentFromFile(File JavaDoc xmlFile) throws IOException JavaDoc, SAXException JavaDoc
199     {
200         InputSource JavaDoc xmlSource = new InputSource JavaDoc(new FileReader JavaDoc(xmlFile));
201         DOMParser parser = new DOMParser();
202         parser.parse(xmlSource);
203         return parser.getDocument();
204     }
205     
206         
207     /**
208      * This method fetches the document-root(DOM) from a xml-document located in a byte[] specified
209      * by user argument.
210      *
211      * @since 2002-12-16
212      * @author Mattias Bogeblad
213      */

214       
215     public static Document JavaDoc readDocumentFromByteArray(byte[] xml) throws IOException JavaDoc, SAXException JavaDoc
216     {
217         InputSource JavaDoc xmlSource = new InputSource JavaDoc(new BufferedInputStream JavaDoc(new ByteArrayInputStream JavaDoc(xml)));
218         DOMParser parser = new DOMParser();
219         parser.parse(xmlSource);
220         Document JavaDoc document = parser.getDocument();
221         parser = null;
222         return document;
223     }
224
225 }
Popular Tags