[英]Correctly removing html entities from a string
我在从字符串中删除 html 实体时遇到问题。 我尝试System.Web.HttpUtility.HtmlDecode
,并希望看到
被替换为常规空间。 相反,会返回一个奇怪的十六进制代码。 我已阅读以下两个主题并了解到这很可能是编码问题,但我找不到解决方法。
如何在不知道字符串中包含哪些标签的情况下从字符串中删除所有 HTML 标签? (“我意识到……”,Thierry_S)
应该从html代码和实体中剥离的源字符串以SQL_Latin1_General_CP1_CI_AI
作为排序SQL_Latin1_General_CP1_CI_AI
保存在数据库中,但对于我的单元测试,我只是在Visual Studio中创建了一个测试字符串,其中的编码不一定与编码相同存储在数据库中的数据。
我的单元测试断言“不等于”,因为
没有替换为常规空间。 最初,它返回2C
,但经过大量测试并尝试从某种编码转换为另一种编码后,即使我已从函数中删除了所有编码更改代码,它现在也返回A0
。
我的问题有两个:
我的功能:
public static string StripHtml(string text)
{
// Remove html entities like
text = System.Net.WebUtility.HtmlDecode(text);
// Init Html Agility Pack
var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(text);
// Return without html tags
return htmlDoc.DocumentNode.InnerText;
}
我的单元测试:
public void StripHtmlTest()
{
// arrange
string html = "<p>This is a very <b>fat, <i>italic</i> and <u>underlined</u> text,<!-- foo bar --> sigh.</p> And 6 < 9 but > 3.";
string actual;
string expected = "This is a very fat, italic and underlined text, sigh. And 6 < 9 but > 3.";
// act
actual = StaticRepository.StripHtml(html);
// assert
Assert.AreEqual(expected, actual);
}
测试结果:
Message: Assert.AreEqual failed. Expected:<This is a very fat, italic and underlined text, sigh. And 6 < 9 but > 3.>. Actual:<This is a very fat, italic and underlined text, sigh. And 6 < 9 but > 3.>.
十六进制测试结果:
嗯
不是“常规”空间。 当您使用System.Net.WebUtility.HtmlDecode
,它将返回命名为 ' ' 的 html 实体的文本表示。 它看起来像普通的空格,但它有不同的含义。 nbsp
的十进制表示实际上是160
,十六进制是A0
,因此您的单元测试和解码工作正常。
如果您想用常规空格替换nbsp
,您有几个选项,其中最简单的是在解码之前执行简单替换:
// where the second argument is whitespace char with decimal representation 32
text = text.Replace(" ", " ");
关于初始运行:十六进制值2C
是十进制44
,即符号','(逗号)。 有没有可能你只是看错了角色?
关于 sql 排序规则:拉丁文一般能够存储 nbsp 符号,所以..我认为这不是问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.