繁体   English   中英

从字符串中正确删除 html 实体

[英]Correctly removing html entities from a string

我在从字符串中删除 html 实体时遇到问题。 我尝试System.Web.HttpUtility.HtmlDecode ,并希望看到  被替换为常规空间。 相反,会返回一个奇怪的十六进制代码。 我已阅读以下两个主题并了解到这很可能是编码问题,但我找不到解决方法。

删除字符串中的 HTML 实体

如何在不知道字符串中包含哪些标签的情况下从字符串中删除所有 HTML 标签? (“我意识到……”,Thierry_S)

应该从html代码和实体中剥离的源字符串以SQL_Latin1_General_CP1_CI_AI作为排序SQL_Latin1_General_CP1_CI_AI保存在数据库中,但对于我的单元测试,我只是在Visual Studio中创建了一个测试字符串,其中的编码不一定与编码相同存储在数据库中的数据。

我的单元测试断言“不等于”,因为  没有替换为常规空间。 最初,它返回2C ,但经过大量测试并尝试从某种编码转换为另一种编码后,即使我已从函数中删除了所有编码更改代码,它现在也返回A0

我的问题有两个:

  1. 如何让我的单元测试通过?
  2. 我的测试是否正确,因为数据库编码可能与我在单元测试中手动输入的文本不同?

我的功能:

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&nbsp;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.>.

十六进制测试结果:文本

&nbsp; 不是“常规”空间。 当您使用System.Net.WebUtility.HtmlDecode ,它将返回命名为 ' ' 的 html 实体的文本表示。 它看起来像普通的空格,但它有不同的含义 nbsp的十进制表示实际上是160 ,十六进制是A0 ,因此您的单元测试和解码工作正常。
如果您想用常规空格替换nbsp ,您有几个选项,其中最简单的是在解码之前执行简单替换:

// where the second argument is whitespace char with decimal representation 32
text = text.Replace("&nbsp;", " "); 

关于初始运行:十六进制值2C是十进制44 ,即符号','(逗号)。 有没有可能你只是看错了角色?

关于 sql 排序规则:拉丁文一般能够存储 nbsp 符号,所以..我认为这不是问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM