如果元素不存在,则检查空值
问题描述:
我正在获取.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
当然,谢谢你的这个 –
答
如果你打算使用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'?此外,您可能想要调用您使用空条件运算符,这就是问题所在 –
答
铸造元素或属性可空类型是不够的。您将获得该值或为null。
var LineComment = (string)element.Element("comment");
或
var LineKey = (string)element.Attribute("name");
公告 - 似乎问题是你正在做的。价值的“空”又名null.Value –
怎么样使用空传播运算符(?'.')就像你在'if'条件下做的...'element.Element(“comment”)?Value'。或者只是'LineComment = element.Element(“comment”)== null? “”:element.Element(“comment”)。Value;' –