How do I retrieve all the HTML elements with the same class attribute?

c# html html-agility-pack xpath


I developing one application in that I using htmlagility dll to get all <div> tags which is same class attributes..
How to get all elements who have same class from whole html page,
I getting top 1 div who having class='myclass' but in,
my case I want to all div tags who have 'myclass' class.

var vardoc = web.Load("<any website url>"); 
var varmyclass = doc.DocumentNode.SelectSingleNode("//div[@class='myclass']"); 

when I used above method then I getting inner html content of the 'myclass' but in my html contents there are many div tags who have class 'myclass'. I want to get all <div> who have same class using HTMLagility or other

9/29/2011 4:56:16 AM

Accepted Answer

Don't select a single node in that case.

You are using SelectSingleNode, which will return only one node.

Use SelectNodes instead:

var varmyclass = doc.DocumentNode.SelectNodes("//div[@class='myclass']");
9/28/2011 6:36:21 PM

Popular Answer

Two issues, first one is that you should be using SelectNodes() instead as the other answers have pointed out since you want to select multiple nodes.

Also, your XPath is a bit restrictive. It will only get div elements which has only one class, myclass but doesn't include those that have multiple classes. I suspect you want to include those as well. Rather than checking if the class is equal, check if it contains it.

var xpath = "//div[contains(@class,'myclass')]";
var query = doc.DocumentNode.SelectNodes(xpath);

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow