使用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