1

I have the following code to find some elements in my HTML and do something with those which have a certain attribute:

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(htmlString);

foreach (HtmlNode div in doc.DocumentNode.SelectNodes("//div[contains(@class,'item')]"))
{
    var hasAttachments = div.Attributes.FirstOrDefault(a => a.Name.Equals("hasattachments"));
    if (hasAttachments.Value.Equals("True"))
    {
        var itemId = div.Attributes.FirstOrDefault(a => a.Name.Equals("itemid")).Value;
        doStuffWithItemId(itemId);
    }
}

I was wondering if I could merge my query to find elements which posses the class and the value of an attribute set to "True", something like this:

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(htmlString);

foreach (HtmlNode div in doc.DocumentNode.SelectNodes("//div[contains(@class,'item')] and //div[@data-hasattachments=\"True\"]"))
{
    var itemId = div.Attributes.FirstOrDefault(a => a.Name.Equals("itemid")).Value;
    doStuffWithItemId(itemId);
}
CodingKuma
  • 413
  • 6
  • 10
TomSelleck
  • 6,706
  • 22
  • 82
  • 151

1 Answers1

1

This isn't really a HAP issue but an xPath one. You can even test the xPath easily in the chrome dev tools. Also you were on the right path just have to put the and in one more layer. I tried this with some mock data and it worked for me.

//div[contains(@class,'item') and @data-hasattachments="True"]

Here is a related SO post. XPath with multiple conditions

CodingKuma
  • 413
  • 6
  • 10