2017-09-07 73 views
0

我正在獲取.resx文件中多個元素的值。在一些data元素<comment>子元素不存在,所以當我運行以下時,我會得到一個NullReferenceException如果元素不存在,則檢查空值

foreach (var node in XDocument.Load(filePath).DescendantNodes()) 
{ 
    var element = node as XElement; 

    if (element?.Name == "data") 
    { 
     values.Add(new ResxString 
     { 
      LineKey = element.Attribute("name").Value, 
      LineValue = element.Value.Trim(), 
      LineComment = element.Element("comment").Value //fails here 
     }); 
    } 
} 

我曾嘗試以下:

LineComment = element.Element("comment").Value != null ? 
       element.Element("comment").Value : "" 

和:

LineComment = element.Element("comment").Value == null ? 
       "" : element.Element("comment").Value 

但是我仍然得到一個錯誤?任何幫助讚賞。

+0

公告 - 似乎問題是你正在做的。價值的「空」又名null.Value –

+0

怎麼樣使用空傳播運算符(?'.')就像你在'if'條件下做的...'element.Element(「comment」)?Value'。或者只是'LineComment = element.Element(「comment」)== null? 「」:element.Element(「comment」)。Value;' –

回答

2

使用Null-conditional?.)操作:

LineComment = element.Element("comment")?.Value 

它曾經前測試空執行成員訪問。

+0

當然,謝謝你的這個 –

2

如果你打算使用LINQ的,不只是部分地使用它: (上S. Akbari's Answer只是擴大)

values = XDocument.Load(filePath) 
    .DescendantNodes() 
    .Select(dn => dn as XElement) 
    .Where(xe => xe?.Name == "data") 
    .Select(xe => new new ResxString 
    { 
     LineKey = element.Attribute("name").Value, 
     LineValue = element.Value.Trim(), 
     LineComment = element.Element("comment")?.Value 
    }) 
    .ToList(); // or to array or whatever 
+2

在你的例子中不會是'xe'?此外,您可能想要調用您使用空條件運算符,這就是問題所在 –

0

鑄造元素或屬性可空類型是不夠的。您將獲得該值或爲null。

var LineComment = (string)element.Element("comment"); 

var LineKey = (string)element.Attribute("name"); 
相關問題