How do I catch the NullReferenceException Error in the foreach loop below if 'SelectNodes' returns NULL?
I searched on stackoverflow and found mention of the null-coalescing condition (?? condition) that can be used to catch this error, however, I have no idea on what the syntax would be for HTMLNode, or if that's even possible.
foreach (HtmlNode link in imagegallery.DocumentNode.SelectNodes("//a[@href]") )
{
//Do Something
}
How would you cath the NULL EXCEPTION for this loop, or is there a better way of doing this?
Here is the full code throwing the exception -
private void TEST_button1_Click(object sender, EventArgs e)
{
//Declarations
HtmlWeb htmlWeb = new HtmlWeb();
HtmlAgilityPack.HtmlDocument imagegallery;
imagegallery = htmlWeb.Load(@"http://adamscreation.blogspot.com/search?updated-max=2007-06-27T10:03:00-07:00&max-results=20&start=18&by-date=false");
foreach (HtmlNode link in imagegallery.DocumentNode.SelectNodes("//a[@imageanchor=1 or contains(@href,'1600')]/@href"))
{
//do something
}
}
if(imagegallery != null && imagegallery.DocumentNode != null){
foreach (HtmlNode link in
imagegallery.DocumentNode.SelectNodes("//a[@href]")
?? Enumerable.Empty<HtmlNode>())
{
//do something
}
}
I was doing this quite a few times so made Andras' solution into an extension method:
using HtmlAgilityPack;
namespace MyExtensions {
public static class HtmlNodeExtensions {
/// <summary>
/// Selects a list of nodes matching the HtmlAgilityPack.HtmlNode.XPath expression.
/// </summary>
/// <param name="htmlNode">HtmlNode class to extend.</param>
/// <param name="xpath">The XPath expression.</param>
/// <returns>An <see cref="HtmlNodeCollection"/> containing a collection of nodes matching the <see cref="XPath"/> expression.</returns>
public static HtmlNodeCollection SelectNodesSafe(this HtmlNode htmlNode, string xpath) {
// Select nodes if they exist.
HtmlNodeCollection nodes = htmlNode.SelectNodes(xpath);
// I no matching nodes exist, return empty collection.
if (nodes == null) {
return new HtmlNodeCollection(HtmlNode.CreateNode(""));
}
// Otherwise, return matched nodes.
return nodes;
}
}
}
Usage:
using MyExtensions;
foreach (HtmlNode link in imagegallery.DocumentNode.SelectNodesSafe("//a[@href]")) {
//Do Something
}