2010-07-31 34 views

回答

8

不,没有。您可以使用Apache Commons LangStringEscapeUtils#escapeHtml4


更新:如果有一个针对第三方库的厌恶和/或喜欢homegrowing,然后在字符串的字符回路和确定在switch字符和转义字符替换它。你可以找到herehere的例子。但是,长期来看,使用StringEscapeUtils更容易。

+0

感谢您的答复 – RMK 2010-08-02 04:56:10

1
public static String encodeHTML(String s) 
{ 
StringBuffer out = new StringBuffer(); 
for(int i=0; i<s.length(); i++) 
{ 
    char c = s.charAt(i); 
      if(c=='<') 
      { 
       out.append("&lt;"+(int)c+";"); 
      } 
      else if(c=='>'){ 
       out.append("&gt;"+(int)c+";"); 
      } 
      else 
      { 
       out.append(c); 
      } 
} 
return out.toString(); 

}

+0

怎么样的&? – 2010-07-31 14:43:44

+0

我编辑我的答案。 – Alex 2010-08-02 04:57:02

0

没有,但你可以写一个:

遍历字符串:

  • 当char是>输出&gt;
  • 当char是<输出&lt;
  • 当char是&输出&amp;
  • 当char unicode值超出32..126输出时&#...;其中...是char unicode值。
  • 其他输出字符