0

我有一個簡單的xml。如何處理NullReferenceException當Linq to xml解析屬性

 var FieldsInData = from fields in xdoc.Descendants("DataRecord") 
          select fields; 

現在我在FildsInData中有n個不同的XElement項目。

 foreach (var item in FieldsInData) 
     { 
      //working 
      String id = item.Attribute("id").Value; 
      //now i get a nullReferenceException because that XElement item has no Attribute called **fail** 
      String notExistingAttribute = item.Attribute("fail").Value; 
     } 

由於該失敗屬性我得到nullReferenceException,因爲它不存在。有時候是,有時並非如此。我如何優雅地處理?

我嘗試使用value.SingleOrDefault();但我得到另一個異常,因爲它是Char的IEnumerable。

回答

0

你只需要檢查null

String notExistingAttribute = ""; 

var attribute = item.Attribute("fail"); 
if(attribute != null) 
    notExistingAttribute = attribute.Value; 
+0

似乎解決了這個問題。 thx – Gero 2012-08-17 13:24:32

2

我想補充另一種方式來做到這一點,你也可以濫用擴展方法爲空檢查:

public static class XmlExtensions 
{ 
    public static string ValueOrDefault(this XAttribute attribute) 
    { 
     return attribute == null ? null : attribute.Value; 
    } 
} 

,然後用它像即:

string notExistingAttribute = item.Attribute("fail").ValueOrDefault(); 
+0

非常非常好! – Gero 2012-08-17 13:41:06

+0

嚴格地說,要遵循'ValueOrDefault'模式,這應該有第二個參數,允許你指定Default。否則,我會把它稱爲'ValueOrNull'。 :-) – Holf 2015-02-27 12:07:24