Arshad Arshad - 15 days ago 5
C# Question

Extract heading text from HTML text

I have a

textarea
with
tinyMCE
text editor to make it RichTextEditor. I want to extract all heading(H1,H2 etc) text without style and formatting .

Suppose that
txtEditor.InnerText
gives me value like below:

<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>


i want to get a list of heading tag's text only ? any kind of suggestion and guidance will be appreciated.

Answer

Use HtmlAgilityPack, and then it's easy :

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