HTML Agility pack + Select node by its inner text

c#-4.0 html-agility-pack xpath

Question

I have gotten the hang of using the html agility pack to find specific nodes using their attributes and xpaths. The problem is, I've been doing this manually for each of my projects (opening the website html and scanning for the nodes that have the text i need). Is there a way to select a single node by its inner text? This would make it easier to write an update script for websites whose content scheme is the same, but attribute tags change values over time. Thanks in advance!

Popular Answer

Would be better if you have provided sample HTML, but since you haven't, let's assume we have HTML containing this markup :

<body>
    <div class="foo">bar</div>
</body>

You can select the <div> by it's attribute using HtmlAgilityPack's SelectSingleNode() and XPath like so :

myHtmlDocument.DocumentNode.SelectSingleNode("//div[@class='foo']");

or you can select the same by the inner text like so :

myHtmlDocument.DocumentNode.SelectSingleNode("//div[.='bar']");

Hope this help.




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