C#對HTML轉譯需要注意的問題

來源:互聯網
上載者:User

標籤:style   blog   http   color   strong   os   

原文:C#對HTML轉譯需要注意的問題

     在做B/S程式時我們多少會用到一點HTML特殊符號轉譯。 如:“&”——>“&amp;” , "<"——>"&lt;" , ">"——>"&gt;" , " "——>"&nbsp;" ...

     符號轉譯成為編碼:

 

        /// <summary>        /// HTMLs the en code.        /// </summary>        /// <param name="sHTML">The HTML.</param>        /// <returns></returns>        public static string HTMLEnCode(string sHTML)        {            string sTemp = "";            if (sHTML.Length == 0)            {                return "";            }            sTemp = sHTML.Replace("<", "&lt;");            sTemp = sTemp.Replace("&", "&amp;");            sTemp = sTemp.Replace(">", "&gt;");            sTemp = sTemp.Replace("‘", "&#39;");            sTemp = sTemp.Replace(" ", "&nbsp;");            sTemp = sTemp.Replace("\"", "&quot;");            sTemp = sTemp.Replace("\n", "<br />");            return sTemp;        }

     當我們需要再轉換成HTML代碼的時候會用到:

 /// <summary>        /// HTMLs the de code.        /// </summary>        /// <param name="sHTML">The HTML.</param>        /// <returns></returns>        public static string HTMLDeCode(string sHTML)        {            string sTemp = "";            if (sHTML.Length == 0)            {                return "";            }            sTemp = sHTML.Replace("&lt;", "<");            sTemp = sTemp.Replace("&gt;", ">");            sTemp = sTemp.Replace("&#39;", "‘");            sTemp = sTemp.Replace("&nbsp;", " ");            sTemp = sTemp.Replace("&quot;", "\"");            sTemp = sTemp.Replace("&amp;", "&");            sTemp = sTemp.Replace("<br />", "\n");            return sTemp;        }

      但是我們往往會忽略最重要的一點, 就是當我們把轉譯符轉換成HTML的時候需要注意一下轉碼的順序,我們必須在 “<”, ">", " " , "‘" ,"\" 這幾個符號轉譯之後最後在轉換 “&”符, 不然,轉譯過後的&後面如果跟有 “nbsp;”這樣連續的字元的時候就會重新轉換成為了空格。

     

     不積跬步,無以至千裡;不積小流,無以成江海。只是在於積累,希望這點發現也可以幫到你!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.