Gerald
Gerald

Reputation: 1083

Convert datetime from xml to c# object using linq

I have the following code below:

XDocument xmldocument = XDocument.Load(xmlfile);
List<Client> clients = (from client in xmldocument.Element("Clients").Elements("Client")
                       select new Client
                       {
                             Name = client.Element("Name").Value,
                             Birthday = Convert.ToDateTime(client.Element("Birthday").Value)
                       }).ToList();

And here is my xml:

 <Clients>
 <Client>
      <Name>Firstname Lastname</Name>
      <Birthday>01/01/1991</Birthday>
 </Client>
 </Clients>

My problem is I am getting a null reference error whenever I tried to run the code. But when I removed the Birthday from the linq statement, I am getting the data so I assumed that there must be something wrong on my converting to date.

Did I missed something here? Thanks!

Upvotes: 1

Views: 1812

Answers (2)

rajeemcariazo
rajeemcariazo

Reputation: 2524

You can use the Parse method:

DateTime.Parse(client.Element("Birthday").Value).Date

or the ParseExact method with the format dd/MM/yyyy

DateTime.ParseExact(client.Element("Birthday").Value, "d/M/yyyy", CultureInfo.InvariantCulture).Date;

or the ParseExact method with the format MM/dd/yyyy

DateTime.ParseExact(client.Element("Birthday").Value, "M/d/yyyy", CultureInfo.InvariantCulture).Date;

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

use XElement to DateTime conversion instead of Convert.ToDateTime:

XDocument xmldocument = XDocument.Load(xmlfile);
List<Client> clients = (from client in xmldocument.Element("Clients").Elements("Client")
                       select new Client
                       {
                             Name = (string)client.Element("Name"),
                             Birthday = (DateTime)client.Element("Birthday")
                       }).ToList();

Upvotes: 3

Related Questions