Reputation: 4070
Let's say I have the following XML:
<Account>
<AccountExpirationDate>6/1/2009</AccountExpirationDate>
</Account>
I want to use LINQ to XML to parse this into an object I'll call Account:
public class Account {
public DateTime? AccountExpirationDate { get; set; }
}
This is the C# code I've tried, but it won't let me use null:
var accountSettings =
from settings in templateXML.Descendants("Account")
select new Account {
AccountExpirationDate =
string.IsNullOrEmpty(settings.Element("AccountExpirationDate").Value)
? DateTime.Parse(settings.Element("AccountExpirationDate").Value)
: null
};
Is there a way for me to only assign AccountExpiration a date if the element exists in the XML? In my business logic it is acceptable for the value to be null. Thanks!
Upvotes: 2
Views: 5904
Reputation: 91
For a more readable syntax and if you need such a check multiple times, you could use extension methods:
public static DateTime? ToDateTime(this Element e)
{
if (e == null)
return null;
if (string.IsNullOrEmpty(e.Value))
return null;
else
return DateTime.Parse(e.Value);
}
Upvotes: 0
Reputation: 1063383
You can just use:
from settings in templateXML.Descendants("Account")
let el = settings.Element("AccountExpirationDate")
let el2 = (el == null || string.IsNullOrEmpty(el.Value)) ? null : el
select new Account {
AccountExpirationDate = (DateTime?)el2
};
there is a conversion operator that works this magic using standard xml datetime formatting, and which returns null if the element doesn't exist (note I don't read .Value
).
Upvotes: 1
Reputation: 422112
var accountSettings =
from settings in templateXML.Descendants("Account")
select new Account {
AccountExpirationDate =
string.IsNullOrEmpty((string)settings.Element("AccountExpirationDate"))
? (DateTime?)null
: DateTime.Parse(settings.Element("AccountExpirationDate").Value)
};
Upvotes: 2
Reputation: 2488
Try:
var accountSettings = from settings in templateXML.Descendants("Account")
where settings.Element("AccountExpriationDate") != null
&& !String.IsNullOrEmpty(settings.Element("AccountExpriationDate").Value)
select new Account
{
AccountExpirationDate = DateTime.Parse(settings.Element("AccountExpirationDate").Value)
};
Upvotes: 0