c# - 如何检查此 C# LINQ to XML 语句中的 NullReferenceException?

标签 c# xml linq

我如何检查此 C# LINQ to XML 语句中的 NullReferenceException 而无需将整个内容包装在 try/catch 中?如果任何属性为空,我希望它仍然尝试获取剩余数据。

谢谢。

XElement doc = XElement.Load("test.xml");

var nodes =
   from node in doc.Elements("Customer")
   select new
   {
       Name = node.Element("FullName").Value,
       Zip = node.Element("ZipCode").Value,
       Active = node.Element("ActiveCustomer").Value,
   }; 

最佳答案

只需使用显式 转换。如果未找到该元素,它将返回 null,不会导致异常。

var nodes =
from node in doc.Elements("Customer")
select new
{
   Name = (string)node.Element("FullName"),
   Zip = (string)node.Element("ZipCode"),
   Active = (string)node.Element("ActiveCustomer"),
}; 

关于c# - 如何检查此 C# LINQ to XML 语句中的 NullReferenceException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25188146/

相关文章:

java - 安卓| SQLite : Pre-created database updating without using SQLiteOpenHelper

c# - 是否可以将所有 'for' 循环替换为 LINQ 语句?

c# - 用 [SomeAttribute] 和 [Some] 装饰类的区别

c# - 如何在 C# 中获取类型的位宽和符号?

C# 更改 DataGridView 中的列标题

linq - 编译 NHibernate Linq 表达式

linq - 识别 linq to sql 查询的来源

c# - dotnet 核心 : Can not find assembly file Microsoft. CSharp.dll

xml - Visual Studio 更改调试 xml 命令行参数

php - 写XML的时候,手写好还是用PHP的simpleXML之类的生成器好?