在我的程序中,我使用了字符串变量内容。我已经为这个字符串分配了一个小的 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/