我需要知道在/ xml中写入/读取DateTime的最佳方式.我应该直接将DateTime写入XML或DateTime.ToString()到XML中.
第二个问题是如何从xml中读取日期元素.可以使用铸造; (DateTime)rec.Element("Date").value或我需要像这样解析字符串DateTime.Parse(rec.Element("Date").value)
Jon*_*eet 18
您可以使用XElement或XAttribute使用LINQ to XML,但是...而不是字符串本身.LINQ to XML使用标准XML格式,与您的文化设置无关.
样品:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
输出给我:
<Now>2011-01-21T06:24:12.7032222+00:00</Now>
21/01/2011 06:24:12
Run Code Online (Sandbox Code Playgroud)
@Jon Skeet的答案的替代方法是使用"往返"格式将DateTime转换为字符串.这会将其转换为可以保存和加载的格式,而不会丢失任何信息.
string dataToSave = myDateTime.ToString("o");
Run Code Online (Sandbox Code Playgroud)
然后使用DateTime.Parse()再次转换回来.我链接到的页面有一些示例,向您展示如何转换为字符串格式/从字符串格式转换.您需要做的就是将此字符串存储到XML中.这使您可以更好地控制数据的存储方式(如果您想要更多控制,那就是).