Java String escape for XML element content

Description

Java String escape for XML element content


//package com.demo2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String s = "";
        System.out.println(escapeXmlContent(s));
    }//from  w  w  w. jav a  2s .co m

    /**
     * Escape a string for use inside as XML element content. This escapes
     * less-than and ampersand, only.
     */
    public static String escapeXmlContent(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
            case '&':
                sb.append("&amp;");
                break;
            case '<':
                sb.append("&lt;");
                break;

            case '\000':
            case '\001':
            case '\002':
            case '\003':
            case '\004':
            case '\005':
            case '\006':
            case '\007':
            case '\010':
            case '\013':
            case '\014':
            case '\016':
            case '\017':
            case '\020':
            case '\021':
            case '\022':
            case '\023':
            case '\024':
            case '\025':
            case '\026':
            case '\027':
            case '\030':
            case '\031':
            case '\032':
            case '\033':
            case '\034':
            case '\035':
            case '\036':
            case '\037':
                // do nothing, these are disallowed characters
                break;
            default:
                sb.append(c);
            }
        }
        return sb.toString();
    }
}



PreviousNext

Related