1 52 53 package freemarker.template.utility; 54 55 import java.io.IOException ; 56 import java.io.Writer ; 57 import java.util.Map ; 58 59 import freemarker.template.TemplateTransformModel; 60 61 70 public class XmlEscape implements TemplateTransformModel { 71 72 private static final char[] LT = "<".toCharArray(); 73 private static final char[] GT = ">".toCharArray(); 74 private static final char[] AMP = "&".toCharArray(); 75 private static final char[] QUOT = """.toCharArray(); 76 private static final char[] APOS = "'".toCharArray(); 77 78 public Writer getWriter(final Writer out, Map args) 79 { 80 return new Writer () 81 { 82 public void write(char c) 83 throws 84 IOException 85 { 86 switch(c) 87 { 88 case '<': out.write(LT, 0, 4); break; 89 case '>': out.write(GT, 0, 4); break; 90 case '&': out.write(AMP, 0, 5); break; 91 case '"': out.write(QUOT, 0, 6); break; 92 case '\'': out.write(APOS, 0, 6); break; 93 default: out.write(c); 94 } 95 } 96 97 public void write(char cbuf[], int off, int len) 98 throws 99 IOException 100 { 101 int lastoff = off; 102 int lastpos = off + len; 103 for (int i = off; i < lastpos; i++) 104 { 105 switch (cbuf[i]) 106 { 107 case '<': out.write(cbuf, lastoff, i - lastoff); out.write(LT, 0, 4); lastoff = i + 1; break; 108 case '>': out.write(cbuf, lastoff, i - lastoff); out.write(GT, 0, 4); lastoff = i + 1; break; 109 case '&': out.write(cbuf, lastoff, i - lastoff); out.write(AMP, 0, 5); lastoff = i + 1; break; 110 case '"': out.write(cbuf, lastoff, i - lastoff); out.write(QUOT, 0, 6); lastoff = i + 1; break; 111 case '\'': out.write(cbuf, lastoff, i - lastoff); out.write(APOS, 0, 6); lastoff = i + 1; break; 112 } 113 } 114 int remaining = lastpos - lastoff; 115 if(remaining > 0) 116 { 117 out.write(cbuf, lastoff, remaining); 118 } 119 } 120 public void flush() throws IOException { 121 out.flush(); 122 } 123 124 public void close() { 125 } 126 }; 127 } 128 } 129 | Popular Tags |