简体   繁体   中英

C# : Read/Write DateTime from/into 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)

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).

您可以使用XmlConvert类在字符串之间进行转换。

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