java实现HTML标签转义和反转义(StringEscapeUtils)

转义:有时需要对带有格式的长文本(如个人文章或评论等)进行转义后存储到数据库表中。

      例如:String EsHtml="

我的
评论

";

                 转义后为"<p>我的<br/>评论</p>"

反转义:数据库中存储的转义后的文本有时需要反转至页面。

      例如:字符串: "<p>我的<br/>评论</p>"

                 反转义后为"

我的
评论

"

        在apache的工具包common-lang中有StringEscapeUtils工具类,可以对HTML标签进行转义和反转义,但是该工具类的转义方法escapeHtml对于中文字符兼容性不是很好,因此需要自定义方法对特殊字符进行处理。

1、HTML标签转义:

      public class test {
      public static void main(String[] args) {
           StringHTMLText="

我的
评论

"; Stringtext=htmlEncode(HTMLText); System.out.println(text); } public static String htmlEncode(String source) { if(source == null) { return ""; } String html = ""; StringBuffer buffer = new StringBuffer(); for(int i = 0; i < source.length(); i++) { char c = source.charAt(i); switch (c) { case '<': buffer.append("<"); break; case '>': buffer.append(">"); break; case '&': buffer.append("&"); break; case '"': buffer.append("""); break; case 10: case 13: break; default: buffer.append(c); } } html = buffer.toString(); return html; } }

输出结果为:<p>我的<br/>评论</p>



2、HTML标签反转义:

public static void main(String[] args) {
	String HTMLText="

我的
评论

"; System.out.println(StringEscapeUtils.unescapeHtml(HTMLText)); } public static void main(String[] args) { String HTMLText="

我的
评论

"; System.out.println(StringEscapeUtils.unescapeHtml(HTMLText)); }

输出结果为:

我的
评论


你可能感兴趣的:(html&xml)