SelectNodes to return empty HtmlNodeCollection if no matching node is found

Topics: Developer Forum
Jan 22, 2009 at 9:22 AM
The current implementation ot the HtmlNode.SelectNodes(string xpath) returns  null if no node matched .
In our version the method was change to return empty HtmlNodeCollection. 

/*MG: Return an empty list if no nodes found.
if (list.Count == 0)
return null;
return list;

It is safer for coding (e.g call foreach(node in nodes) without warry if nodes are null) and consistent with XmlNode..::.SelectNodes .
 I recommend to apply the change to master version.

However I understand that it could be considered as "breaking" change.

Oct 16, 2009 at 3:02 PM

I second this...

May 14, 2012 at 8:12 PM

I thought SelectNodes would be used in a LINQ fashion .... I was shocked when it returned null while I was trying to enumerate few elements ...

come on guys its 2012 and this is LINQ world now ... it should return an empty collection rather than null 

May 14, 2012 at 8:30 PM

Then use the LINQ interfaces of Descendants and Elements.

SelectNodes matches the .NET System.Xml API for which it was built upon.

I agree this should be overhauled to return an empty list but the fact is there are thousands of applications out there that could break if this is changed in a minor point release. There were new LINQ like functions added of Descendants, Elements and DescendantNodes to more closely match the LINQ to XML interface.

This is one of the things I wanted to address in 2.0 if I can ever get the time to work on it. The actual current implementation with HtmlNodeCollection needs to be tossed out and replaced with a yield return and an IEnumerable<HtmlNode> return type;

For the people that want this, an extension method can solve it

public static IList<HtmlNode> SelectNodesAsList(this HtmlNode node, string xpath)
	var list = node.SelectNodes(xpath);
	if (list == null)
		return new List<HtmlNode>();

	return list;


Aug 26, 2014 at 4:03 PM
Returning null is the most non-intuitive thing that could be done. Under what circumstances is an empty collection fundamentally different than null?