C# : Read/Write DateTime from/into XML
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
An alternative to @Jon Skeet's answer is to convert the DateTime to a string using the "round trip" format. This converts it to a format that will save and load without losing any information.
string dataToSave = myDateTime.ToString("o");
And convert back again using DateTime.Parse(). The page I've linked to has examples showing you how to convert to/from the string format. All you need to do is store this string into your XML. THis gives you more control over how the data is stored (if you want more control, that is).
You can use the XmlConvert class to convert to and from strings.