View Javadoc
1   package gboat2.base.bridge.util.xml;
2   
3   import java.io.IOException;
4   import java.io.Writer;
5   
6   import com.sun.org.apache.xml.internal.utils.XML11Char;
7   import com.sun.xml.bind.marshaller.CharacterEscapeHandler;
8   
9   /**
10   * 对 XML 特殊字符进行转义处理的类
11   * @author <a href="mailto:[email protected]">何明旺</a>
12   * @since 3.0
13   * @date 2014年4月1日
14   */
15  public class XmlCharacterEscapeHandler implements CharacterEscapeHandler {
16      
17      /**
18       * Escape characters inside the buffer and send the output to the writer.
19       * 
20       * @exception IOException if something goes wrong, IOException can be thrown to stop the marshalling process.
21       */
22      @Override
23      public void escape(char[] buf, int start, int len, boolean isAttValue, Writer out) throws IOException {
24          for (int i = start; i < (start + len); i++) {
25              char ch = buf[i];
26  
27              // you are supposed to do the standard XML character escapes like & ... &amp; < ... &lt; etc
28              if (ch == '&') {
29                  out.write("&amp;");
30                  continue;
31              }
32  
33              if (ch == '<') {
34                  out.write("&lt;");
35                  continue;
36              }
37  
38              if (ch == '>') {
39                  out.write("&gt;");
40                  continue;
41              }
42  
43              if ((ch == '"') && isAttValue) {
44                  // isAttValue is set to true when the marshaller is processing attribute values.
45                  // Inside attribute values, there are more things you need to escape, usually.
46                  out.write("&quot;");
47                  continue;
48              }
49  
50              if ((ch == '\'') && isAttValue) {
51                  out.write("&apos;");
52                  continue;
53              }
54  
55              // you should handle other characters like < or >
56              if (ch > 0x7F) {
57                  // escape everything above ASCII to &#xXXXX;
58                  out.write("&#x");
59                  out.write(Integer.toHexString(ch));
60                  out.write(";");
61                  continue;
62              }
63  
64              // use apache util to check for valid xml character
65              if (XML11Char.isXML11Valid(ch)) {
66                  out.write(ch);
67              }
68          }
69      }
70  }