代码之家  ›  专栏  ›  技术社区  ›  RB.

如何在visualbasic.NET中对Em-Dash进行“HTML编码”

  •  0
  • RB.  · 技术社区  · 16 年前

    HttpUtility.HtmlEncode Em Dash (应转换为“-”)号。

    sWebsiteText = _
        "<![CDATA[" & _
        HttpUtility.HtmlEncode(sSomeText) & _
        "]]>"
    
    'This is the bit which seems "hacky"'
    sWebsiteText = _
        sWebsiteText.Replace(HttpUtility.HtmlDecode("&#8211;"), "&#8211;")
    

    所以我的问题是-你将如何实现“黑客”部分?

    非常感谢,,

    3 回复  |  直到 16 年前
        1
  •  3
  •   bobince    16 年前

    由于此字符不是ASCII字符,如何对其进行编码?

    它不是ASCII字符,而是Unicode字符,U+2014。如果您的页面输出将是UTF-8,在当今这个时代它确实应该是UTF-8,那么您不需要对其进行HTML编码,只需直接输出字符即可。

    是否还有其他角色可能给我带来问题。

    它到底给你带来了什么问题?如果无法输出“-”,则可能无法输出任何其他非ASCII Unicode字符,这是数千个字符。

    如果确实需要,请将“\u2014”替换为“&x2014;”,但实际上,使用今天的支持Unicode的工具,不必到处用标记替换每个非ASCII Unicode字符。

        2
  •  0
  •   Community Neeleshkumar S    7 年前

    看看 A List Apart ,正如我在 HTML Apostrophe

    &#8212;

        3
  •  0
  •   Frederic Frederic    15 年前

    Bobince的回答为您主要关心的问题提供了一个解决方案:用一个更直接的要替换的字符声明来替换您对HTMLDE代码的使用。
    重写

    sWebsiteText.Replace(HttpUtility.HtmlDecode("&#8211;"), "&#8211;")
    


    sWebsiteText.Replace("\u2013", "&#x2013;")
    

    (“\u2014”(dec 8212)是em破折号,\u2013”(dec 8211)是en破折号。)
    出于可读性目的,可能认为使用“&x2013;”比使用“&8211;”更好,因为字符(“\u2013”)的.Net声明也是十六进制的。但是,由于十进制符号在html中似乎更常见,我个人更喜欢使用“&8211;”。
    出于重用的目的,您可能应该编写在自定义HttpUtility中声明的自己的HtmlEncode函数,以便能够从站点中的任何其他位置调用它,而无需复制它。
    (比如(抱歉,我用C#编写了它,忘记了你的示例是用VB编写的):

    /// <summary>
    /// Supplies some custom processing to some HttpUtility functions.
    /// </summary>
    public static class CustomHttpUtility
    {
        /// <summary>
        /// Html encodes a string.
        /// </summary>
        /// <param name="input">string to be encoded.</param>
        /// <returns>A html encoded string.</returns>
        public static string HtmlEncode(string input)
        {
            if (intput == null)
                return null;
            StringBuilder encodedString = new StringBuilder(
                HttpUtility.HtmlEncode(input));
            encodedString.Replace("\u2013", "&#x2013;");
            // add over missing replacements here, as for &#8212;
            encodedString.Replace("\u2014", "&#x2014;");
            //...
    
            return encodedString.ToString();
        }
    }
    

    然后替换

    sWebsiteText = _
        "<![CDATA[" & _
        HttpUtility.HtmlEncode(sSomeText) & _
        "]]>"
    'This is the bit which seems "hacky"'
    sWebsiteText = _
        sWebsiteText.Replace(HttpUtility.HtmlDecode("&#8211;"), "&#8211;")
    


    sWebsiteText = _
        "<![CDATA[" & _
        CustomHttpUtility.HtmlEncode(sSomeText) & _
        "]]>"
    

    )