Java String escape for XML

Description

Java String escape for XML

//package com.demo2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String s = "&&demo2s.com'''&&&";
        System.out.println(xmlEscape(s));
    }/*from   ww w  .  j  a  v  a 2 s  .c  om*/

    /**
     * Returns a form of "s" appropriate for including in an XML document, after
     * escaping certain special characters (e.g. '&' => '&', etc.)
     */
    public static String xmlEscape(String s) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            switch (ch) {
            case '"':
                sb.append("&quot;");
                break;
            case '&':
                sb.append("&amp;");
                break;
            case '\'':
                sb.append("&apos;");
                break;
            case '<':
                sb.append("&lt;");
                break;
            case '>':
                sb.append("&gt;");
                break;
            case '\n':
                sb.append("&#xA;");
                break;
            case '\r':
                sb.append("&#xD;");
                break;
            case '\t':
                sb.append("&#x9;");
                break;
            case '\0':
                // \0 is not a valid XML char - skip it
                break;
            default:
                sb.append(ch);
                break;
            }
        }
        return sb.toString();
    }

}



PreviousNext

Related