我有一個簡單的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。
似乎解決了這個問題。 thx – Gero 2012-08-17 13:24:32