博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C#中HTML字符转换函数

Posted on 2012-07-27 13:49  moss_tan_jun  阅读(385)  评论(0编辑  收藏  举报

在ASP.Net中经常会从网面中取数据或更新网页的显示。因为HTML中有些特殊字符如<, >, &等,显示实际值不一致,造成保存到数据库再取出来时会不一样。因此需要以下函数做转换:

///<summary>
        ///替换html中的特殊字符
        ///</summary>
        ///<paramname="theString">需要进行替换的文本。</param>
        ///<returns>替换完的文本。</returns>
        public static string HtmlEncode(string theString)
        {
            theString=theString.Replace(">","&gt;");
            theString=theString.Replace("<","&lt;");
            theString=theString.Replace(" ","&nbsp;");
            theString=theString.Replace("\"","&quot;");
            theString = theString.Replace("\'", "&#39;");
            theString=theString.Replace("\n","<br/>");
            return theString;
        }

        ///<summary>
        ///恢复html中的特殊字符
        ///</summary>
        ///<paramname="theString">需要恢复的文本。</param>
        ///<returns>恢复好的文本。</returns>
        public static string HtmlDiscode(string theString)
        {
            theString=theString.Replace("&gt;",">");
            theString=theString.Replace("&lt;","<");
            theString=theString.Replace("&nbsp;"," ");
            theString=theString.Replace("&quot;","\"");
            theString = theString.Replace("&#39;", "\'");
            theString=theString.Replace("<br/>","\n");
            return theString;
        }