30 Nov 2009

The other day, I was using for the first time the Html Agility Pack library.

The method I use the most is the SelectNodes to which you give an XPath and that returns an HtlmNodeCollection containing the resulting HtmlNodes or null if no node where found.

I don’t know if this is a design decision, but returning null when there is no match is not very nice. If you use the expression as is in a foreach statement, it will throw a NullReferenceException if no match.

A simple solution is to use the coalescing operator next to the function’s call, in order to give the foreach an empty Enumerable to avoid the exception.

htmlNode.SelectNodes(xpath) ?? Enumerable.Empty<HtmlNode>()

This is working well, but it’s a bit ugly to repeat that in every foreach statement.

This is where Extension Methods are so enjoyable. Let’s just add a new method to our HtmlNode friend that returns an empty enumerable when SelectNodes return null.

internal static class HtmlAgilityPackExtension
    internal static IEnumerable<HtmlNode> SelectNodesOrEmpty(this HtmlNode htmlNode, String xpath)
        return htmlNode.SelectNodes(xpath) ?? Enumerable.Empty<HtmlNode>();

There we go. From now on, I can simply foreach over a SelectNodesOrEmpty result of any HtmlNode, with no fear of any exception.

blog comments powered by Disqus