【发布时间】:2011-05-15 18:28:20
【问题描述】:
我似乎无法弄清楚如何将 ISO-8859-1 字符(例如 é)转换为它的实体编号 é。
我希望能够取一个字符串,例如:“Steel Décor”
并将其转换为:“Steel Décor”
【问题讨论】:
标签: c# encode iso-8859-1
我似乎无法弄清楚如何将 ISO-8859-1 字符(例如 é)转换为它的实体编号 é。
我希望能够取一个字符串,例如:“Steel Décor”
并将其转换为:“Steel Décor”
【问题讨论】:
标签: c# encode iso-8859-1
假设您不关心 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écor"
if 语句可能需要更改为转义字符 < 0x20 或非字母数字等,具体取决于您的具体需求。
【讨论】:
HttpUtility.HtmlEncode 这样做。它驻留在 System.Web.dll 中,但不适用于 .NET 4 客户端配置文件。
【讨论】:
使用 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;
}
【讨论】: