Java 怎么使用XML实体转义字符串中的字符

2019年8月2日23:29:43Java 怎么使用XML实体转义字符串中的字符已关闭评论 545 1192字阅读3分58秒

1.简介

Java 怎么使用XML实体转义字符串中的字符?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;

public class Main{
    public static void main(String[] argv){
        String src = "tah1986.com";
        System.out.println(escape(src));
    }
    private static final String[] ESCAPES;

    static {
        int size = '>' + 1; 
        ESCAPES = new String[size];
        ESCAPES['<'] = "<";
        ESCAPES['>'] = ">";
        ESCAPES['&'] = "&";
        ESCAPES['\''] = "'";
        ESCAPES['"'] = """;
    }
    
    
    public static String escape(String src) {

        if (src == null) {
            return src;
        }

        
        
        int length = 0;
        for (int i = 0; i < src.length(); i++) {
            char c = src.charAt(i);
            String escape = getEscape(c);
            if (escape != null) {
                length += escape.length();
            } else {
                length += 1;
            }
        }

        
        if (length == src.length()) {
            return src;
        }

        
        StringBuilder buf = new StringBuilder(length);
        for (int i = 0; i < src.length(); i++) {
            char c = src.charAt(i);
            String escape = getEscape(c);
            if (escape != null) {
                buf.append(escape);
            } else {
                buf.append(c);
            }
        }
        return buf.toString();
    }
    
    public static String escape(boolean shouldEscape, String src) {
        if (shouldEscape) {
            return escape(src);
        }
        return src;
    }
    private static String getEscape(char c) {
      if (c < ESCAPES.length) {
          return ESCAPES[c];
      } else {
          return null;
      }
  }
}

 
继续阅读
编程十万个怎么办