从HTML文本中提取标题文本

时间:2013-01-09 13:58:45

标签: c# asp.net html

我有textarea tinyMCE文本编辑器,可以将其作为RichTextEditor。我想提取没有样式和格式的所有标题(H1,H2等)文本。
假设txtEditor.InnerText给我的价值如下:

<p><span style="font-family: comic sans ms,sans-serif; color: #993366; font-size: large; background-color: #33cccc;">This is before heading one</span></p>
<h1><span style="font-family: comic sans ms,sans-serif; color: #993366;">Hello This is Headone</span></h1>
<p>this is before heading2</p>
<h2>This is heading2</h2>

我想获得标题标签的文字列表吗?任何建议和指导将不胜感激。

2 个答案:

答案 0 :(得分:3)

使用HtmlAgilityPack,然后很容易:

  var doc = new HtmlDocument();
  doc.LoadHtml(txtEditor.InnerText);
  var h1Elements = doc.DocumentNode.Descendants("h1").Select(nd => nd.InnerText);
  string h1Text = string.Join(" ", h1Elements);

答案 1 :(得分:0)

引用Regular Expression to Read Tags in HTML
我相信这接近你所寻找的:

String h1Regex = "<h[1-5][^>]*?>(?<TagText>.*?)</h[1-5]>";

MatchCollection mc = Regex.Matches(html, h1Regex);
相关问题