2012-07-03 22 views
4

如何捕獲NullReferenceException如果'SelectNodes'返回的foreach循環出錯NULLNullReferenceException在使用HTMLNode的foreach循環中的錯誤

我在stackoverflow上搜索並發現提到可用於捕獲此錯誤的空合併條件(??條件),但是,我不知道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 
      } 
    }  
+0

你可以發表你的logcat的錯誤及整個代碼.. –

+0

...添加它,正在加載的網頁不包含XPath的引用節點,所以我假定的NullReferenceException是由引起...有沒有辦法使用空合併運算符? –

回答

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

您將具有相同的錯誤,如果'SelectNodes'返回'NULL' ... –

+0

我以爲,如果沒有找到的SelectNodes將返回一個空的枚舉(這是做了正確的事情 - 但是這是問題的範圍)。有一個空COALESCE更新'Enumerable.Empty ()'' –

+1

SelectNodes'確實返回null如果沒有匹配的節點。 – Rawling

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