Escape XML or HTML string. - Java XML

Java examples for XML:XML String Escape

Description

Escape XML or HTML string.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String str = "java2s.com";
        System.out.println(escape(str));
    }//  w  w  w  .j a  v  a 2s.  c  o m

    /**
     * Escape XML or HTML string.
     *
     * @param str input string
     * @return escaped string
     */
    public static String escape(String str) {

        StringBuffer buf = new StringBuffer();
        char ch;

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

        for (int i = 0; i < str.length(); i++) {
            ch = str.charAt(i);

            switch (ch) {
            case '<':
                buf.append("&lt;");
                break;

            case '>':
                buf.append("&gt;");
                break;

            case '&':
                buf.append("&amp;");
                break;

            case '"':
                buf.append("&quot;");
                break;

            case '\'':
                buf.append("&apos;");
                break;

            default:
                buf.append(ch);
            }
        }

        return buf.toString();
    }
}

Related Tutorials