>Does any one know of a method in Java or Servlet package to encode string to
>HTML format?
>
>For example:
>  <name>John</name>
>
>After encoding:
>&lt;name&gt;John&lt;/name&gt;

I guess you need it to present exactly what you have in
a string without getting it intepreted as HTML.

Since "<", ">"  and "&" are the only characters to care for,
it's easy to write yourself:

1. Replace all "&" by "&amp;"
2. Replace "<" and ">" by "&lt;" and "&gt;"

My version (does not replace ">") reads:


    /**
     * escape character of string which
     * have HTML special meanings
     *
     * (replace '<' by '&lt;' and '&' by '&amp;')
     */
    static public String escapeAllHTML(String s) {
        return stringReplace(stringReplace(s, "&", "&amp;"), "<", "&lt;");
    }
    static private String stringReplace(String s, String what, String by) {
        int start=0, l = s.length();

        int i = s.indexOf(what, 0);
        if(i < 0) {
            // nothing to escape
            return s;
        }
        int wl = what.length();

        StringBuffer sb = new StringBuffer(l + 1024);

        while(i >= 0) {
            if(start < i)
                sb.append(s.substring(start, i));
            sb.append(by);
            start = i+wl;
            i = s.indexOf(what, start);
        }
        if(start <= l) {
            sb.append(s.substring(start));
        }
        return sb.toString();
    }



>
>Hien
>
>===========================================================================
>To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
>of the message "signoff JSP-INTEREST".  For general help, send email to
>[EMAIL PROTECTED] and include in the body of the message "help".

Ciao,
        Carsten Heyl

  Carsten Heyl                          [EMAIL PROTECTED]
  NADS - Solutions on Nets              http://www.nads.de/
  NADS GmbH                             http://www.pixelboxx.de/
  Hildebrandtstr. 4E                    Tel.: +49 211 933 02-90
D-40215 Duesseldorf                     Fax.: +49 211 933 02-93

===========================================================================
To unsubscribe, send email to [EMAIL PROTECTED] and include in the body
of the message "signoff JSP-INTEREST".  For general help, send email to
[EMAIL PROTECTED] and include in the body of the message "help".

Reply via email to