I am using HTML Agility Pack and searching for div
with class="fileHeader"
that has "RelayClinical Patient Education with Animations Install zip"
in a child h4 element. Once found, I want to capture the "href"
attribute inside the anchor tag of that particular block. How can I get it?
HTML Source
<div class="fileHeader" id="fileHeader_7311111">
<h4 class="collapsed">RelayClinical Patient Education with Animations Install zip</h4>
<div class="defaultMethod">
<a class="buttonGrey" href="https://mckc-esd.subscribenet.com/cgi-bin/download?rid=2511740931&rp=DTM20130905162949MzcyODIwNjM0" title="Clicking this link will open a new window." rel="noreferrer">
HTTPS Download
</a>
</div>
</div>
Code
HtmlNodeCollection fileHeaderNodes = bodyNode.SelectNodes("//div[@class='fileHeader']//h4");
foreach (HtmlNode fileHeader in fileHeaderNodes)
{
if (fileHeader.InnerText.Trim() == "RelayClinical Patient Education with Animations Install zip")
{
HtmlNodeCollection fileHeaderNodes = bodyNode.SelectNodes("//div[@class='fileHeader']//h4");
foreach (HtmlNode fileHeader in fileHeaderNodes)
{
if (fileHeader.InnerText.Trim() == "RelayClinical Patient Education with Animations Install zip")
{
foreach (HtmlNode link in fileHeader.SelectNodes("//a[@href]"))
{
// extract the link and put in dataUrl var
if ((link.InnerText.Trim() == "HTTPS Download") && isFound == true)
{
count++;
// select all a tags (html anchor tags) that have a href attribute
HtmlAttribute att = link.Attributes["href"];
dataUrl = att.Value;
}
}
}
}
}
}
Rather than selecting the h4
element, select the a
element directly. Then you can grab the href
attribute.
var h4Text = "RelayClinical Patient Education with Animations Install zip";
var xpath = String.Format(
"//div[@class='fileHeader' and h4='{0}']/div[@class='defaultMethod']/a",
h4Text
);
var anchor = doc.DocumentNode.SelectSingleNode(xpath);
if (anchor != null)
{
var attr = anchor.GetAttributeValue("href", null);
// do stuff with attr
}