Search code examples
c#browserhtml-agility-pack

Get HtmlAgilityPack Node using exact HTML search or Converting HTMLElement to HTMLNode


I have created a HTMLElement picker (DOM) by using the default .net WebBrowser. The user can pick (select) a HTMLElement by clicking on it.

I want to get the HtmlAgilityPack.HTMLNode corresponding to the HTMLElement.

The easiest way (in my mind) is to use doc.DocumentNode.SelectSingleNode(EXACTHTMLTEXT) but it does not really work (because the function only accepts xpath code).

How can I do this?

A sample HTMLElement select by a user looks like this (The OuterHtml Code):

<a onmousedown="return wow" class="l" href="http://site.com"><em>Great!!!</em> <b>come and see more</b></a>

Of course, any element can be selected, that's why I need a way to get the HTMLNode.


Solution

  • Same concept, but a bit simpler because you don't have to know the element type:

    HtmlNode n = doc.DocumentNode.Descendants().Where(n => n.OuterHtml.Equals(text, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();