使用HTMLNode的foreach循環中的NullReferenceException錯誤

c# foreach html-agility-pack nullreferenceexception

如果'SelectNodes'返回NULL,如何在下面的foreach循環中捕獲NullReferenceException錯誤?

我在stackoverflow上搜索並發現可以用來捕獲此錯誤的null-coalescing條件(??條件),但是,我不知道HTMLNode的語法是什麼,或者甚至可能。

foreach (HtmlNode link in imagegallery.DocumentNode.SelectNodes("//a[@href]") )
            {
                //Do Something
            }

你會如何為這個循環選擇NULL 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
  }
}

熱門答案

我這樣做了很多次,所以Andras的解決方案變成了擴展方法:

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;
        }
    }
}

用法:

using MyExtensions;

foreach (HtmlNode link in imagegallery.DocumentNode.SelectNodesSafe("//a[@href]")) {
    //Do Something
}


Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow