c# - 如何从c#中的html代码中获取html代码的一部分?

标签 c# html

在我的程序中,我使用了字符串变量内容。我已经为这个字符串分配了一个小的 HTML 程序。例如,

String content = "<HTML> <HEAD> <TITLE>Your Title Here</TITLE></HEAD> <BODY><H2>This is a Medium Header Send me mail at<a href="mailto:support@yourcompany.com">support@yourcompany.com</a>.This is a new sentence without a paragraph break.</H2></BODY></HTML>";

从这里我想得到“这是一个中等标题 请发送邮件至 support@yourcompany.com。这是一个没有分段的新句子。”单独。

此字符串在标签内可用。我如何使用 C# 获取此字符串。

最佳答案

不要使用字符串方法或正则表达式来解析 HTML。您可以使用 HtmlAgilityPack .

string content = "<HTML> <HEAD> <TITLE>Your Title Here</TITLE></HEAD> <BODY><H2>This is a Medium Header Send me mail at<a href=\"mailto:support@yourcompany.com\">support@yourcompany.com</a>.This is a new sentence without a paragraph break.</H2></BODY></HTML>";

var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(content);
string headerText = doc.DocumentNode.Descendants("H2").First().InnerText;

结果:

This is a Medium Header Send me mail atsupport@yourcompany.com.This is a new sentence without a paragraph break.

关于c# - 如何从c#中的html代码中获取html代码的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30121263/

相关文章:

c# - 打开并阅读命令提示符命令

java - 如何将 jscolor 选择器设置为 bs 按钮

javascript - 在 MathML 渲染中使用命名空间

c# - 使用 Specflow 和 xUnit 2 (ITestOutputHelper) 进行日志记录

c# - 当多个输入具有相同的 "Name"时,如何使用 WatiN 填充特定输入字段?

html - 为什么我的代码中不显示背景图像?

html - 将文本放在图像旁边的 Bootstrap 行底部

html - css中的笔荧光笔效果

c# - 我如何找出当前的 UnhandledExceptionMode

c# - SomeMethod(() => x.Something) 在 C# 中是什么意思