Convert a string to html content, Same as the xml version except that spaces and tabs are converted. - Java XML

Java examples for XML:XML String Escape

Description

Convert a string to html content, Same as the xml version except that spaces and tabs are converted.

Demo Code


//package com.java2s;

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

    /**
     * Convert a string to html content, Same as the xml version
     * except that spaces and tabs are converted.
     * @param tabIcon the icon to represent a tag.
     * @param str     the string to convert.
     * @return the converted string.
     */
    public static String escapeHTMLContent(String tabIcon, String str) {
        final StringBuilder b = new StringBuilder();
        final char[] chars = str.toCharArray();
        for (int i = 0; i < chars.length; ++i) {
            final char c = chars[i];
            switch (c) {
            case '<':
                b.append("&lt;");
                break;
            case '>':
                b.append("&gt;");
                break;
            case '&':
                b.append("&amp;");
                break;
            case ' ':
                b.append("&nbsp;");
                break;
            case '\t':
                b.append("<img src='" + tabIcon + "' title='tab'/>");
                b.append("&nbsp;");
                break;
            default:
                b.append(c);
            }
        }
        return b.toString();
    }
}

Related Tutorials