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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With