2017-08-03 2430 views
-1

我創建的程序需要從網站讀取信息並存儲。我得到錯誤:c#System.ArgumentNullException:值不能爲空。參數名稱:來源

System.ArgumentNullException: Value cannot be null.
Parameter name: source
at System.Linq.Enumerable.Select[TSource,TResult](IEnumerable 1 source, Func 2 selector)

但它並不總是運行錯誤。正如有時它有效,有時它不起作用。怎麼會這樣? 這是給我的錯誤行此異常落後4

IEnumerable<string> webtemp = Enumerable.Empty<string>(); 
if (datastring.Contains("today_nowcard-temp")) 
{ 
    webtemp = doc.DocumentNode.SelectNodes("//div[@class = 'today_nowcard-temp']/span").Select(d => d.InnerText.Trim()); 

    foreach (var this_header in webtemp) 
    { 
     string[] temporary = this_header.Trim().Replace("Â", "-").Replace(" ", "-").Split('-'); 
     int f = (Convert.ToInt32(temporary[0])); 
     _actualData[0].temp = GetCelsius(f); 
     //Console.WriteLine(_actualData[0].temp); 
    } 
} 
+3

空校驗這個'DocumentNode.SelectNodes(「// DIV [@class =‘today_nowcard-TEMP’] /跨度」)'返回一個空,但沒有看到你所擁有的'doc'不可能說出爲什麼xpath不返回結果。 – rene

+0

它有時會返回一個結果,而且我可以告訴xpath不會改變。 –

+0

我們需要看到您的文檔的xml是@rene正在獲取的。 – GibralterTop

回答

2

原因是由您的SelectNodes方法的返回值的代碼。有時候它會返回null,然後你嘗試對null執行Linq操作,並且它會產生錯誤。所以,你可以對這個

var temp= doc.DocumentNode.SelectNodes("//div[@class = 'today_nowcard-temp']/span"); 

if(temp != null){ 
//TODO 
} 
相關問題