Skip to content Skip to sidebar Skip to footer

How To Get Next 2 Nodes In Html + Htmlagilitypack

I have a table in the HTML code below:

My Regional Financial Office

Solution 1:

You can use following XPath :

var htmlDoc = new HtmlDocument();
htmlDoc.LoadHtml(html);
var tdOfInterests = 
        htmlDoc.DocumentNode
               .SelectNodes("//tr[td/h3[.='My Address']]/following-sibling::tr[position() <= 2]/td");
foreach (HtmlNode td in tdOfInterests)
{
    //given html input in question following code will print following 2 lines://000 Test Ave S Ste 000//Golden Valley, MN 00000
    Console.WriteLine(td.InnerText);
}

The key of above XPath is using following-sibling with position() filter.

UPDATE :

A bit explanation about the XPath used in this answer :

//tr[td/h3[.='My Address']]

above part select <tr> element that has :

  • child <td> element that has child <h3> element with value equals 'My Address'

/following-sibling::tr[position() <= 2]

next part select following <tr> element with position <=2 from current <tr> element (the one selected by previous XPath part)

/td

the last part select child <td> element from current <tr> element

Post a Comment for "How To Get Next 2 Nodes In Html + Htmlagilitypack"