简体   繁体   中英

How can I check for a NullReferenceException in this C# LINQ to XML statement?

How can I check for a NullReferenceException in this C# LINQ to XML statement without wrapping the whole thing in a try/catch? If any of the properties are null, I would like it to still attempt to get the remaining data.

Thanks.

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,
   }; 

Just use explicit cast. It will return null if the element wasn't found, won't cause an exception.

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"),
}; 

Use the ternary operator.

Ternary Operator

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

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

You could try this one:

select new
{
    Name = node.Element("FullName")!=null ? node.Element("FullName").Value : null,
    Zip = node.Element("ZipCode")!=null ? node.Element("ZipCode").Value : null,
    Active = node.Element("ActiveCustomer")!=null ? node.Element("ActiveCustomer").Value : null
}; 

The ? is the conditional operator. For further documentation about this, please have a look here .

you can use ternary operator to check for null .

do like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM