Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# : Read/Write DateTime from/into XML

Tags:

c#

xml

I need to know the optimal way of writing/reading DateTime into/from XML. Should I directly write DateTime into XML or DateTime.ToString() into XML?

Second question is how to read the date element from XML. Can casting be used for this? Eg:

(DateTime)rec.Element("Date").value

Or, do I need to parse the string like this? Eg:

DateTime.Parse(rec.Element("Date").value)

like image 339
Pankaj Upadhyay Avatar asked Jan 21 '11 06:01

Pankaj Upadhyay


1 Answers

You can use casting of an XElement or XAttribute with LINQ to XML, yes... but not of the string itself. LINQ to XML uses the standard XML format, independent of your culture settings.

Sample:

using System;
using System.Xml.Linq;

class Test
{    
    static void Main()
    {
        DateTime now = DateTime.Now;
        XElement element = new XElement("Now", now);

        Console.WriteLine(element);
        DateTime parsed = (DateTime) element;
        Console.WriteLine(parsed);
    }
}

Output for me:

<Now>2011-01-21T06:24:12.7032222+00:00</Now>
21/01/2011 06:24:12
like image 159
Jon Skeet Avatar answered Sep 17 '22 18:09

Jon Skeet