使用HTMLNode的foreach循环中的NullReferenceException错误

时间:2012-07-03 07:14:06

标签: 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
            }
    }       

3 个答案:

答案 0 :(得分:8)

if(imagegallery != null && imagegallery.DocumentNode != null){
  foreach (HtmlNode link in 
    imagegallery.DocumentNode.SelectNodes("//a[@href]") 
      ?? Enumerable.Empty<HtmlNode>()) 
  {
    //do something
  }
}

答案 1 :(得分:0)

您可以分两步完成,在使用之前测试集合是否为NULL:

if (imagegallery != null && imagegallery.DocumentNode != null)
{
    HtmlNodeCollection linkColl = imagegallery.DocumentNode.SelectNodes("//a[@href]");

    if (linkColl != NULL)
    {
        foreach (HtmlNode link in linkColl)
        {
           //Do Something
        }
    }
}

答案 2 :(得分:0)

我这样做了很多次,所以让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
}