Reputation: 13574
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)
Upvotes: 8
Views: 29884
Reputation: 1840
You can use the XmlConvert class to convert to and from strings.
Upvotes: 5
Reputation: 57902
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).
Upvotes: 7
Reputation: 1500225
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
Upvotes: 20