HttpUtility.HtmlDecode 无法解码 '
本文关键字:解码 HtmlDecode HttpUtility | 更新日期: 2023-09-27 18:34:51
我正在使用.net 4.5和
HttpUtility.HtmlDecode
无法解码'
哪个是单引号字符
知道为什么吗?
在 Windows 8.1 上使用 C# .net 4.5 WPF
这里失败的文本
Apple 13'' Z0RA30256 MacBook Pro Retina
以下是框架版本
#region Assembly System.Web.dll, v4.0.0.0
// C:'Program Files (x86)'Reference Assemblies'Microsoft'Framework'.NETFramework'v4.5'System.Web.dll
#endregion
使用构建的 it HtmlDecode
方法无法处理此问题,您必须查找/替换它或以其他方式变通。
下面是HtmlDecode
的源代码 - 您可以从注释中明确看到您的方案被考虑且不受支持 - HTML 实体必须与;
绑定,否则它们根本不是 HTML 实体。浏览器可以原谅不正确的标记,并相应地进行补偿。
// We found a '&'. Now look for the next ';' or '&'. The idea is that
// if we find another '&' before finding a ';', then this is not an entity,
// and the next '&' might start a real entity (VSWhidbey 275184)
这是 .NET HtmlDecode
的完整源代码 HttpUtility
,如果你想适应行为。
http://referencesource.microsoft.com/#System/net/System/Net/WebUtility.cs,44d08941e6aeb00d
public static void HtmlDecode(string value, TextWriter output)
{
if (value == null)
{
return;
}
if (output == null)
{
throw new ArgumentNullException("output");
}
if (value.IndexOf('&') < 0)
{
output.Write(value); // good as is
return;
}
int l = value.Length;
for (int i = 0; i < l; i++)
{
char ch = value[i];
if (ch == '&')
{
// We found a '&'. Now look for the next ';' or '&'. The idea is that
// if we find another '&' before finding a ';', then this is not an entity,
// and the next '&' might start a real entity (VSWhidbey 275184)
int index = value.IndexOfAny(_htmlEntityEndingChars, i + 1);
if (index > 0 && value[index] == ';')
{
string entity = value.Substring(i + 1, index - i - 1);
if (entity.Length > 1 && entity[0] == '#')
{
// The # syntax can be in decimal or hex, e.g.
// å --> decimal
// å --> same char in hex
// See http://www.w3.org/TR/REC-html40/charset.html#entities
ushort parsed;
if (entity[1] == 'x' || entity[1] == 'X')
{
UInt16.TryParse(entity.Substring(2), NumberStyles.AllowHexSpecifier, NumberFormatInfo.InvariantInfo, out parsed);
}
else
{
UInt16.TryParse(entity.Substring(1), NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out parsed);
}
if (parsed != 0)
{
ch = (char)parsed;
i = index; // already looked at everything until semicolon
}
}
else
{
i = index; // already looked at everything until semicolon
char entityChar = HtmlEntities.Lookup(entity);
if (entityChar != (char)0)
{
ch = entityChar;
}
else
{
output.Write('&');
output.Write(entity);
output.Write(';');
continue;
}
}
}
}
output.Write(ch);
}
}