HtmlAgilityPack SelectNodes Syntax

.net c# html html-agility-pack xpath

Question

I have the following HTML:

<tbody>
    <tr>
        <td class="metadata_name">Headquarters</td>
        <td class="metadata_content">Princeton New Jersey, United States</td>
    </tr>
    <tr>
        <td class="metadata_name">Industry</td>
        <td class="metadata_content"><ul><li><a href="/q-Engineering-Software-jobs.html" rel="nofollow">Engineering Software</a></li><li><a href="/q-Software-Development-&amp;-Design-jobs.html" rel="nofollow">Software Development &amp; Design</a></li><li><a href="/q-Software-jobs.html" rel="nofollow">Software</a></li><li><a href="/q-Custom-Software-&amp;-Technical-Consulting-jobs.html" rel="nofollow">Custom Software &amp; Technical Consulting</a></li></ul></td>
    </tr>
    <tr>
        <td class="metadata_name">Revenue</td>
        <td class="metadata_content">$17.5 Million</td>
    </tr>
    <tr>
        <td class="metadata_name">Employees</td>
        <td class="metadata_content">201 to 500</td>
    </tr>
    <tr>
        <td class="metadata_name">Links</td>
        <td class="metadata_content"><ul><li><a href="/url?q=http%3A%2F%2Fwww.site.com&amp;h=085df2ca" target="_blank">Company website</a></li></ul></td>
    </tr>
</tbody>

I want to be able to load the metadata_content value (ex "$17.5 Million") in to a var where the metadata_name is = to a value (ex: "Revenue").

I have tried to use combinations of code like this for a few hours...

orgHtml.DocumentNode.SelectNodes("//td[@class='metadata_name']")[0].InnerHtml;

But I'm not getting the right combination down. If you have a helpful SelectNodes syntax - that will get me the solution I would appreciate it.

Accepted Answer

It seems what you're looking for is this:

var found = orgHtml.DocumentNode.SelectSingleNode(
    "//tr[td[@class = 'metadata_name'] = 'Revenue']/td[@class = 'metadata_content']");
if (found != null)
{
    string html = found.InnerHtml;
    // use html
}

Note that to get the text of an element, you should use found.InnerText, not found.InnerHtml, unless you specifically need its HTML content.




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