This project has moved. For the latest updates, please go here.
4
Vote

1.4.9.5: SelectNodes causes NullReferenceException

description

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.

comments

galmok wrote Sep 22, 2016 at 10: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 1:17 AM

Doomjunky wrote Nov 1, 2016 at 1: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 5:42 AM

wrote Dec 28, 2016 at 5:45 AM

bjarteao wrote Jan 25 at 11:45 AM

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.