2013-09-05 29 views
0

我正在使用HTML Agility Pack并搜索divclass="fileHeader",它在子h4元素中有"RelayClinical Patient Education with Animations Install zip"。一旦找到,我想要捕获该特定块的锚标记内的"href"属性。我怎么才能得到它?使用HTML Agility Pack选择下一个元素

HTML源

<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&amp;rp=DTM20130905162949MzcyODIwNjM0" title="Clicking this link will open a new window." rel="noreferrer"> 
      HTTPS Download 
     </a> 
    </div> 
</div> 

代码

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

回答

0

而不是选择h4元件,直接选择a元件。然后你可以获取href属性。

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 
} 
+0

我知道有一个更简单的解决方案!谢谢杰夫的回答,那是一张黄金票。 – user2751629

相关问题