2

我似乎无法弄清楚如何将 ISO-8859-1 字符(例如 é)转换为它的实体编号é

我希望能够取一个字符串,例如:“Steel Décor”

并将其转换为:“Steel D écor”

4

3 回答 3

3

假设您不关心 HTML 中特殊的 HTML 编码字符(例如,<、& 等),对字符串的简单循环将起作用:

string input = "Steel Décor";
StringBuilder output = new StringBuilder();
foreach (char ch in input)
{
    if (ch > 0x7F)
        output.AppendFormat("&#{0};", (int) ch);
    else
        output.Append(ch);
}
// output.ToString() == "Steel D&#233;cor"

if语句可能需要更改为也转义字符< 0x20或非字母数字等,具体取决于您的确切需求。

于 2010-11-25T16:27:23.360 回答
1

HttpUtility.HtmlEncode这样做。它驻留在 System.Web.dll 中,但不能与 .NET 4 客户端配置文件一起使用。

于 2010-11-25T15:09:17.183 回答
1

使用 LINQ

string toDec(string input)
{
    Dictionary<string, char> resDec =
        (from p in input.ToCharArray() where p > 127 select p).Distinct().ToDictionary(
            p => String.Format(@"&#x{0:D};", (ushort)p));

    foreach (KeyValuePair<string, char> pair in resDec)
        input = input.Replace(pair.Value.ToString(), pair.Key);
    return input;
}
于 2011-03-25T07:07:51.157 回答