Reputation: 4359
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,
};
Upvotes: 1
Views: 100
Reputation: 62488
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
};
Upvotes: 2
Reputation: 101691
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"),
};
Upvotes: 6
Reputation: 53958
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.
Upvotes: 3
Reputation: 5689
Use the 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
};
Upvotes: 3