This project has moved and is read-only. For the latest updates, please go here.
Vote SelectNodes causes NullReferenceException


This simple little code causes NullReferenceException:
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml("<a>Hello World!</a>");
foreach(HtmlNode link in doc.DocumentNode.SelectNodes("//img"))
I was expecting the iterator to simply skip the loop as no img tags are found.


galmok wrote Sep 22, 2016 at 11:56 AM

I just found someone commenting on this particular issue and the gist is that SelectNodes isn't returning en empty list, but returns null. It is basically not Linq capable.

wrote Nov 1, 2016 at 2:17 AM

Doomjunky wrote Nov 1, 2016 at 2:30 AM

I voted for this request.

The good old XmlNode.SelectNodes() and Regex.Matches() have the same behavior. They return an empty collection. It's just a best practice to return an empty list instead of null.

For SelectSingleNode() it's fine to return null when nothing was found.

wrote Dec 28, 2016 at 6:42 AM

wrote Dec 28, 2016 at 6:45 AM

bjarteao wrote Jan 25 at 12:45 PM

Here's a vote to change the behaviour of SelectNodes to return Enumerable.Empty<HtmlNode>() when it doesn't find any matching nodes.

Returning null is not what you expect.