简体   繁体   中英

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!

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();

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;

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