Search code examples
c#htmlxpathhtml-agility-pack

how can i get following-sibling using HtmlAgilityPack?


i have many tr tags in html code:

<div class="noticeTabBoxWrapper">
 <tr>
  <td>
   <span>Text for anchor</span>
  </td>
 </tr>
 <tr>
  <td>
   <span>*constantly changing text*</span>
  </td>
 </tr>

In my code i write this:

//div[@class = 'noticeTabBoxWrapper']//span[contains(text(), 'Text for anchor')]").InnerText

How can I rewrite code so that I can extract the necessary text that follows immediately after the anchor? Thanks.


Solution

  • Assuming raw is your sample data :

    var doc = new HtmlDocument();
    doc.LoadHtml(raw);
    var xpath = "//div[@class='noticeTabBoxWrapper']//span[contains(., 'Text for anchor')]/following::td[1]/span";
    var result = doc.DocumentNode.SelectSingleNode(xpath);
    Console.WriteLine(result.InnerText)
    

    Output : *constantly changing text*