我似乎无法弄清楚如何将 ISO-8859-1 字符(例如 é)转换为它的实体编号é
。
我希望能够取一个字符串,例如:“Steel Décor”
并将其转换为:“Steel D é
cor”
我似乎无法弄清楚如何将 ISO-8859-1 字符(例如 é)转换为它的实体编号é
。
我希望能够取一个字符串,例如:“Steel Décor”
并将其转换为:“Steel D é
cor”
假设您不关心 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;
}