HtmlAgilityPack method for returning value from a row in a table given column data

c# html-agility-pack

Question

I want to use Html Agility pack to extract inner html info based on it's relative distance from other td's within a given row in a table.

For example in the code below what would be an efficient dynamic command that would take the data in the first td tag as an input and give the data in the third td tag as an output:

<tbody>
    <tr>
        <td>Smith</td>
        <td>Glasnevin</td>
        <td>11</td>
        <td>6.0</td>
    </tr>
    <tr>
        <td>Harty</td>
        <td>Blackrock</td>
        <td>11</td>
        <td>6.0</td>
    </tr>
    <tr>
        <td>Power</td>
        <td>Salthill</td>
        <td>0</td>
        <td>5.8</td>
    </tr>
</tbody>

So if I give 'Smith' as an input I'd like to get '11' as an output or if I give 'Power' as an input I'd get '0' as an output.

Accepted Answer

Here is an example :

HtmlDocument doc = new HtmlDocument();
//load your HTML to `doc`
var result = doc.DocumentNode
                .SelectSingleNode("//tr[td[1]='Power']/td[3]")
                .InnerText;
//at this point `result` hold value of 0

The XPath means select <tr> node having first child node <td> equals "Power", then get the third <td> from the aforementioned <tr>.



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