0

I'm getting started with Html Agility Pack but I'm struggling with it throwing a NullReferenceException for items I know for a fact exists.

For example, take this code:

doc.DocumentNode.Descendants("div").ToList()[2]

This returns a valid HtmlNode on which I can do node.Attributes["id"] and get the value of the id attribute ("somevalue" in this case).

However, if I try to get this specific element based on the attribute value I get a NullReferenceException:

doc.DocumentNode.Descendants("div").FirstOrDefault(e => e.Attributes["id"].Value == "somevalue")

Why does this code throw a NullReferenceException when an element with this attribute and this value actually exist?

TheHvidsten
  • 4,028
  • 3
  • 29
  • 62
  • Can you provide the xml file? – Kalten Sep 13 '19 at 20:52
  • 2
    Because there's at least one descendant `div` that does not have an id attribute. – Heretic Monkey Sep 13 '19 at 20:52
  • @HereticMonkey That could definitely explain it. How can you select a child node based on an attribute value where not all children are guaranteed to have this attribute? – TheHvidsten Sep 13 '19 at 20:53
  • 2
    Check if the attribute exists first. I don't know Html Agility Pack, but you could do `e => e.Attributes["id"]?.Value == "somevalue"`, using the [safe navigation operator](https://blogs.msdn.microsoft.com/jerrynixon/2014/02/26/at-last-c-is-getting-sometimes-called-the-safe-navigation-operator/) (a.k.a. null-conditional operator) to make sure it is found. See [C# elegant way to check if a property's property is null](https://stackoverflow.com/q/3468250/215552) – Heretic Monkey Sep 13 '19 at 20:56
  • The xpath query can be `//div/@id[not(.="")]` – Kalten Sep 13 '19 at 21:10
  • @HereticMonkey The null-conditional operator did the trick. Thanks! :) – TheHvidsten Sep 13 '19 at 21:12

0 Answers0