c# - 如何仅对 HTML 字符串中的文本内容进行 HtmlEncode?

标签 c# html asp.net-mvc-3

我有一些 HTML 内容,我想在将其显示在我的网页中之前对其进行解析和编码。

诀窍是我只想对文本内容进行编码,而不是对 HTML 内容中明显的 HTML 标记进行编码。我怎样才能做到这一点?

例子:

提供

"Some text & links : <strong>bla blà blö</strong> and <a href="http://www.google.com">go there</a> for only 15 € < 20 €"

我要输出

"Some text &amp; links : <strong>bla bl&agrave; bl&ouml;</strong> and <a href="http://www.google.com">go there</a> for only 15 &euro; &lt; 20 &euro;"
or
"Some text &#38; links : <strong>bla bl&#224; bl&#246;</strong> and <a href="http://www.google.com">go there</a> for only 15 &#8364; &#60; 20 &#8364;"

最佳答案

使用Html Agility Pack :

var html = 
  "Some text & links : <strong>bla blà blö</strong> and <a href=\"http://www.google.com\">go there</a> for only 15 € < 20 €";

// This
HtmlAgilityPack.HtmlEntity.Entitize(html);

// Outputs
Some text & links : <strong>bla bl&agrave; bl&ouml;</strong> and <a href="http://www.google.com">go there</a> for only 15 &euro; < 20 &euro;

刚刚对其进行了测试,它在您的示例中运行良好。

如果你想看看它是怎么做到的,那就是public .

关于c# - 如何仅对 HTML 字符串中的文本内容进行 HtmlEncode?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7418498/

相关文章:

c# - MVCSiteMapProvider 不会使用 Razor 菜单模板

c# - 通过 lambdas 构造 where 的表达式

asp.net-mvc-3 - 在 Razor View 中显示列表元素

asp.net-mvc-3 - mvc 3站点地图提供程序-指向同一节点的多个路径

c# - 在函数中验证自定义类的类型

html - 重新调整不同图像的大小而不失真

html - 在 HTML 中设置自定义 anchor

javascript - jQuery AutoNumeric 不格式化多个字段

asp.net-mvc - 如何强制链接使用特定路由(MVC路由)

c# - EPPlus - 保存在内存中创建的 excel 并在 excel 上打开它会出错