Java 怎么编码XML

2019年8月9日22:17:52Java 怎么编码XML已关闭评论 523 1269字阅读4分13秒

1.简介

Java 怎么编码XML?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */





public class Main {
    public static void main(String[] argv) {
        String text = "tah1986.com";
        System.out.println(xmlEncode(text));
    }

    
    public static String xmlEncode(String text) {
        return xmlEncode(text, null);
    }

    
    public static String xmlEncode(String text,
            String invalidCharReplacement) {
        if (text == null || text.length() == 0) {
            return text;
        }

        int length = text.length();
        StringBuffer ret = new StringBuffer(length * 12 / 10);
        int last = 0;

        for (int i = 0; i < length; i++) {
            char c = text.charAt(i);
            if (Character.isISOControl(c) && c != '\t' && c != '\r'
                    && c != '\n') {
                last = appendText(text, ret, i, last);
                if (invalidCharReplacement == null) {
                    
                    ret.append(c);
                } else if ("".equals(invalidCharReplacement)) {
                    
                    continue;
                } else {
                    
                    ret.append(invalidCharReplacement);
                }
            } else {
                switch (c) {
                case '&':
                    last = appendText(text, ret, i, last);
                    ret.append("&");
                    break;
                case '>':
                    last = appendText(text, ret, i, last);
                    ret.append(">");
                    break;
                case '<':
                    last = appendText(text, ret, i, last);
                    ret.append("<");
                    break;
                case '\"':
                    last = appendText(text, ret, i, last);
                    ret.append(""");
                    break;
                case '\'':
                    last = appendText(text, ret, i, last);
                    ret.append("'");
                    break;
                default:
                    break;
                }
            }
        }
        appendText(text, ret, length, last);
        return ret.toString();
    }

    private static int appendText(String text, StringBuffer ret,
            int current, int old) {
        if (old < current) {
            ret.append(text.substring(old, current));
        }
        return current + 1;
    }
}

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