使用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,還是有更好的方法呢?

這是拋出異常的完整代碼 -

foreach (HtmlNode link in imagegallery.DocumentNode.SelectNodes("//a[@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 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;
        }
    }
}



許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因