public string GetLogName(string config)
{
XDocument xDoc = XDocument.Load(config);
XElement[] elements = xDoc.Descendants("listeners").Descendants("add").ToArray();
foreach (var element in elements)
{
if (element.Attribute("fileName").Value != null)
{
string filename = element.Attribute("fileName").Value;
int location = filename.IndexOf("%");
Console.WriteLine("string to return: " + filename.Substring(0, location));
return filename.Substring(0, location);
}
}
}
我正在嘗試從元素陣列中的每個元素的「文件名」屬性,但也有一些情況下,當「文件名」屬性不存在與失敗出現以下錯誤:NullReferenceException未處理。你調用的對象是空的。的NullReferenceException是嘗試檢索配置時未處理的錯誤屬性
在我的情況下,有兩個「添加」節點沒有「文件名」屬性,但第三個添加節點有它。
如何跳過沒有「fileName」屬性的條目,或者您能否推薦更好的方式來檢索此屬性?
幾乎'NullReferenceException'的所有情況都是一樣的。請參閱「[什麼是.NET中的NullReferenceException?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)」的一些提示。 –