C#:读/写日期时间从/成XML [英] C# : Read/Write DateTime from/into XML
问题描述
我需要知道写作的最佳方式/读取日期时间到/从XML。我应该直接写日期时间为XML或则DateTime.ToString()为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.
第二个问题是如何读取从XML日期元素。可浇铸用于此; (DATETIME)rec.Element(DATE)。值或我需要解析这样的字符串 DateTime.Parse(rec.Element(DATE)。值)
Second question is how to read the date element from xml. Can casting be used for this ; (DateTime)rec.Element("Date").value or i need to parse the string like this DateTime.Parse(rec.Element("Date").value)
推荐答案
您可以使用的铸造的XElement
或 XAttribute
使用LINQ到XML,是的......但不是字符串本身。 。LINQ到XML采用标准的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.
示例:
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#:读/写日期时间从/成XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!