2013-10-17 34 views
0
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」屬性的條目,或者您能否推薦更好的方式來檢索此屬性?

+0

幾乎'NullReferenceException'的所有情況都是一樣的。請參閱「[什麼是.NET中的NullReferenceException?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)」的一些提示。 –

回答

0

的一種方法是在處理之前過濾出列表:

XElement[] elements = xDoc.Descendants("listeners") 
          .Descendants("add") 
          .Where (d => d.Attribute("filename") != null) 
          .ToArray(); 

---恕我直言,這是我會怎樣改寫方法,使用LINQ和正則表達式---

var elements = 
XDocument.Load(config); 
     .Descendants("listeners") 
     .Descendants("add") 
     .Where (node => node.Attribute("filename") != null) 
     .ToList(); 


return elements.Any() ? elements.Select (node => node.Attribute("filename").Value) 
           .Select (attrValue => Regex.Match(attrValue, "([^%]+)").Groups[1].Value) 
           .First() 
         : string.Empty; 
+0

@Pam謝謝......查看關於重寫的建議。請注意.Select擴展名是一個項目擴展名,用於將數據從一個表單更改爲另一個表單......功能非常強大。 GL – OmegaMan

+0

我決定使用這種方法來篩選出其他節點,而不是在之後進行檢查。我不知道如何編寫這個查詢的where子句,所以這真的有所幫助。謝謝! – Pam

0

你應該能夠做到這一點只需改變這一行:

if (element.Attribute("fileName").Value != null) 

要:

if (element.Attribute("fileName") != null) 
0

變化if語句來這是你的:

if (element.Attribute("fileName") != null) 
相關問題