Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullReferenceException ERROR in foreach loop using HTMLNode

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
            }
    }       
like image 979
Chris L Avatar asked Feb 20 '23 23:02

Chris L


1 Answers

if(imagegallery != null && imagegallery.DocumentNode != null){
  foreach (HtmlNode link in 
    imagegallery.DocumentNode.SelectNodes("//a[@href]") 
      ?? Enumerable.Empty<HtmlNode>()) 
  {
    //do something
  }
}
like image 51
Andras Zoltan Avatar answered Mar 05 '23 16:03

Andras Zoltan