HTML Agility Pack - Get all links of a class

html-agility-pack

Question

I want to get all the links inside a with a certain class.

An example of the HTML is

<tr>
<td>
    <a class="dn-index-link" href="/dailynotes/symbol/659/-1/e-mini-sp500-june-2013">
        ES M3
    </a>
</td>
<td>
    <a href="/dailynotes/symbol/659/-1/e-mini-sp500-june-2013">
        E-mini S&amp;P500 June 2013
    </a>
</td>
</tr>

If I want to get all the links that have the class class="dn-index-link"

what would be my XPath and HTML Agility code?

Thanks, Will.

Accepted Answer

A code like this in a Console Application will dump the content of the HREF attribute for all A nodes (at any level in the whole document) with a CLASS attribute equal to 'dn-index-link' (Click here for a good XPATH tutorial):

HtmlDocument doc = new HtmlDocument();
doc.Load("mytest.htm");

foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//a[@class='dn-index-link']"))
{
    Console.WriteLine("node:" + node.GetAttributeValue("href", null));
}



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why