KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > fr > dyade > aaa > util > XMLWriter


1 /*
2  * Copyright (C) 2000 ScalAgent Distributed Technologies
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
17  * USA.
18  *
19  */

20
21 package fr.dyade.aaa.util;
22
23 import java.io.*;
24
25 public class XMLWriter {
26
27   /**
28    * Prints a string with quotes and quoted special characters.
29    *
30    * @param out stream to write the string to
31    * @param str string to write
32    *
33    * @exception Exception
34    * unspecialized exception
35    */

36   public static void print(PrintWriter out, String JavaDoc str) throws Exception JavaDoc {
37     if (str == null) {
38       out.print("\"\"");
39       return;
40     }
41
42     out.print('"');
43     int max = str.length();
44     for (int i = 0; i < max; i ++) {
45       // gets the numeric value of the unicode character
46
int b = (int) str.charAt(i);
47       if ((b >= 32) && (b <= 126)) {
48     // ASCII printable character, includes special characters
49
// '"', '\'', '<', '>', '&', '%'
50
switch (b) {
51     case (int) '"':
52       out.write("&quot;");
53       break;
54     case (int) '\'':
55       out.write("&apos;");
56       break;
57     case (int) '<':
58       out.write("&lt;");
59       break;
60     case (int) '>':
61       out.write("&gt;");
62       break;
63     case (int) '&':
64       out.write("&amp;");
65       break;
66     case (int) '%':
67       out.write("&#x25;");
68       break;
69     default:
70       out.write(b);
71       break;
72     }
73       } else {
74     if (b == 0) {
75       out.write("&#x0;");
76     } else {
77       int[] xvalue = new int[4];
78       int len = 0;
79       while (b > 0) {
80         xvalue[len] = b & 0xf;
81         if (xvalue[len] < 10)
82           xvalue[len] += (int) '0';
83         else
84           xvalue[len] += ((int) 'a') - 10;
85         b >>= 4;
86         len ++;
87       }
88       out.write("&#x");
89       while (len-- > 0)
90         out.write(xvalue[len]);
91       out.write(';');
92     }
93       }
94     }
95     out.print('"');
96   }
97 }
98
Popular Tags