如果元素不存在则检查空值
Checking for null values if element does not exist
我正在获取 .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
但是我仍然收到错误消息?任何帮助表示赞赏。
使用Null-conditional (?.
)运算符:
LineComment = element.Element("comment")?.Value
它用于在 执行成员访问之前测试 null 。
如果您要使用 Linq,请不要只是部分使用它:
(只是扩展 )
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
将元素或属性转换为可空类型就足够了。您将获得值或 null。
var LineComment = (string)element.Element("comment");
或
var LineKey = (string)element.Attribute("name");
我正在获取 .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
但是我仍然收到错误消息?任何帮助表示赞赏。
使用Null-conditional (?.
)运算符:
LineComment = element.Element("comment")?.Value
它用于在 执行成员访问之前测试 null 。
如果您要使用 Linq,请不要只是部分使用它:
(只是扩展
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
将元素或属性转换为可空类型就足够了。您将获得值或 null。
var LineComment = (string)element.Element("comment");
或
var LineKey = (string)element.Attribute("name");