1 29 30 package com.caucho.xml.stream; 31 32 import com.caucho.util.CharBuffer; 33 import com.caucho.vfs.WriteStream; 34 35 import java.io.IOException ; 36 37 public class Escapifier { 38 39 public static String escape(String s) 40 { 41 if (s == null) 42 return ""; 43 44 CharBuffer cb = null; 45 int len = s.length(); 46 47 for (int i = 0; i < len; i++) { 48 char c = s.charAt(i); 49 50 if (c >= 32 && c <= 127 && c != '&' && c!='<' && c!='>' && c!='\"' 51 || Character.isWhitespace(c)) { 52 if (cb != null) cb.append(c); 53 continue; 54 } 55 56 if (cb == null) { 57 cb = new CharBuffer(); 58 cb.append(s.substring(0, i)); 59 } 60 switch(c) { 61 case '&': cb.append("&"); break; 62 case '<': cb.append("<"); break; 63 case '>': cb.append(">"); break; 64 case '\"': cb.append("""); break; 66 default: cb.append("&#"+((int)(c & 0xffff))+";"); break; 67 } 68 } 69 70 if (cb == null) 71 return s; 72 73 return cb.toString(); 74 } 75 76 public static void escape(String s, WriteStream ws) 77 throws IOException 78 { 79 ws.print(escape(s)); 80 } 81 82 public static void escape(char []buffer, int offset, int len, 83 WriteStream out) 84 throws IOException 85 { 86 for (int i = 0; i < len; i++) { 87 char ch = buffer[offset + i]; 88 89 switch (ch) { 90 case '&': 91 out.print("&"); 92 break; 93 case '<': 94 out.print("<"); 95 break; 96 case '>': 97 out.print(">"); 98 break; 99 case '\"': 101 out.print("""); 102 break; 103 104 case ' ': case '\t': case '\r': case '\n': 105 out.print(ch); 106 break; 107 108 default: 109 if (32 <= ch && ch <= 127) 110 out.print(ch); 111 else 112 out.print("&#" + ((int) ch) + ";"); 113 break; 114 } 115 } 116 } 117 } 118 | Popular Tags |