1 26 27 package net.sourceforge.groboutils.util.xml.v1; 28 29 30 37 public class XMLUtil 38 { 39 protected static XMLUtil s_instance = new XMLUtil(); 40 41 private static final char LOWER_RANGE = 0x20; 48 private static final char UPPER_RANGE = 0x7f; 49 50 private static final char VALID_CHAR_1 = 0x9; 54 private static final char VALID_CHAR_2 = 0xA; 55 private static final char VALID_CHAR_3 = 0xD; 56 57 58 private static final char[] IN_RANGE_INVALID = 59 { '<', '>', '"', '\'', '&' }; 60 private static final String IN_RANGE_VALID[] = 63 { "<", ">", """, "'", "&" }; 64 65 protected XMLUtil() 66 { 67 } 69 70 71 public static XMLUtil getInstance() 72 { 73 return s_instance; 74 } 75 76 78 79 80 92 public String utf2xml( String javaStr ) 93 { 94 if (javaStr == null) 95 { 96 return null; 97 } 98 StringBuffer sb = new StringBuffer (); 99 utf2xml( javaStr, sb ); 100 return sb.toString(); 101 } 102 103 104 160 public void utf2xml( String javaStr, StringBuffer output ) 161 { 162 if (output == null) 163 { 164 throw new IllegalArgumentException ("No null StringBuffer"); 165 } 166 if (javaStr == null) 167 { 168 171 output.append("null"); 174 return; 175 } 176 int len = javaStr.length(); 177 output.ensureCapacity( output.length() + (len * 2) ); 180 181 char buf[] = javaStr.toCharArray(); 183 for ( int pos = 0; pos < len; ++pos) 184 { 185 char c = buf[pos]; 186 if ( 188 (c < LOWER_RANGE && 191 c != VALID_CHAR_1 && c != VALID_CHAR_2 && c != VALID_CHAR_3) 192 || 193 (c > UPPER_RANGE) 194 ) 195 { 196 output.append( "&#" ); 197 output.append( Integer.toString( c ) ); 198 output.append( ';' ); 199 } 200 else 201 { 202 boolean notfound = true; 204 for (int p2 = IN_RANGE_INVALID.length; --p2 >= 0;) 205 { 206 if (IN_RANGE_INVALID[p2] == c) 207 { 208 notfound = false; 209 output.append( IN_RANGE_VALID[ p2 ] ); 210 break; 211 } 212 } 213 if (notfound) 214 { 215 output.append( c ); 217 } 218 } 219 } 220 } 221 } 222 223 | Popular Tags |