我需要知道将 DateTime
写入/读取 XML 的最佳方式。我应该直接将 DateTime
写入 XML 还是将 DateTime.ToString()
写入 XML?
第二个问题是如何从 XML 中读取日期元素。类型转换可以用于此吗?例如:
(DateTime)rec.Element("Date").value
或者,我需要像这样解析字符串吗?例如:
DateTime.Parse(rec.Element("Date").value)
最佳答案
您可以将 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);
}
}
我的输出:
<Now>2011-01-21T06:24:12.7032222+00:00</Now>
21/01/2011 06:24:12
关于C# : Read/Write DateTime from/into XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4755991/