Adam Adam - 1 year ago 234
C# Question

Html Agility Pack get all elements by class

I am taking a stab at html agility pack and having trouble finding the right way to go about this.

For example:

var findclasses = _doc.DocumentNode.Descendants("div").Where(d => d.Attributes.Contains("class"));

However, obviously you can add classes to a lot more then divs so I tried this..

var allLinksWithDivAndClass = _doc.DocumentNode.SelectNodes("//*[@class=\"float\"]");

But that doesn't handle the cases where you add multiple classes and "float" is just one of them like this..

class="className float anotherclassName"

Is there a way to handle all of this? I basically want to select all nodes that have a class = and contains float.

**Answer has been documented on my blog with a full explanation at: Html Agility Pack Get All Elements by Class

Dai Dai
Answer Source

Just add more clauses to your predicate:

var findclasses = _doc.DocumentNode
    .Where(d => 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download