我有大量自动生成的类,使用.NET XmlSerializer从XML序列化/反序列化。其中一些类包含DateTime属性。
我需要使用特定格式序列化所有 DateTime属性,例如“u”。 :
System.DateTime.Now.ToString("u");
//returns something like "2008-06-15 21:15:07Z"
Deserialize方法似乎适用于这种格式,但序列化没有 - 它只是给我硬编码格式与我在托管系统中默认的相同格式(也许我可以通过更改线程设置欺骗序列化器?) (检查更新#1)。
注意: 我已经检查过几个相关问题,通过修改原始属性和添加新属性来解决它们。对我来说,由于我必须进行大量的修改,这是不可接受的。
以下是我用来测试此问题的示例测试类。
using System;
using System.Linq;
using System.Text;
using System.Xml;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.Globalization;
using System.IO;
namespace FunkyTests
{
[TestClass]
public class SerializationTests
{
[TestMethod]
public void FunkySerializationTest()
{
var date = DateTime.Now;
var dummy = new Dummy() { DummyProperty = date };
var xml = SerializeToXml(dummy);//serializes with "o" format
var expected = date.ToString("u", new CultureInfo("en-US"));//in this example I want "u" format
var actual = XDocument.Parse(xml).Descendants("DummyProperty").Single().Value;
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void FunkyDeserializationTest()
{
var date = DateTime.Now;
var dummy = new Dummy() { DummyProperty = date };
var xml = SerializeToXml(dummy);//serializes with "o" format
var deserializedDummy = DeserializeFromXml<Dummy>(xml);
Assert.AreEqual(dummy.DummyProperty, deserializedDummy.DummyProperty);
}
private static T DeserializeFromXml<T>(string xml)
{
using (var textReader = new StringReader(xml))
{
using (var reader = XmlReader.Create(textReader))
{
var serializer = new XmlSerializer(typeof(T));
var result = serializer.Deserialize(reader);
return (T)result;
}
}
}
private static string SerializeToXml<T>(T objectToSerialize)
{
var xml = new StringBuilder();
using (var writer = XmlWriter.Create(xml, new XmlWriterSettings { OmitXmlDeclaration = true }))
{
var ns = new XmlSerializerNamespaces();
ns.Add(string.Empty, string.Empty);
var serializer = new XmlSerializer(typeof(T));
serializer.Serialize(writer, objectToSerialize, ns);
}
return xml.ToString();
}
public class Dummy
{
public DateTime DummyProperty { get; set; }
}
}
}
任何时髦的想法?
更新#1: 我认为日期序列化依赖于Thread.CurrentCulture。如果我正确解释XmlSerializer代码,格式是硬编码的(谢谢ILSpy)。
// System.Xml.Serialization.XmlCustomFormatter
internal static string FromDateTime(DateTime value)
{
if (XmlCustomFormatter.Mode == DateTimeSerializationSection.DateTimeSerializationMode.Local)
{
return XmlConvert.ToString(value, "yyyy-MM-ddTHH:mm:ss.fffffffzzzzzz");
}
return XmlConvert.ToString(value, XmlDateTimeSerializationMode.RoundtripKind);
}
更新#2:我添加了一个测试方法,该方法使用Alexander Petrov提出的答案。它没有断言Ticks。根据{{3}}问题是在DateTime的内部,并且是由于丢失了DateTime的“Kind”。建议使用DateTimeOffset,这导致了另一个序列化问题,在Serialize DateTime as binary中解释
答案 0 :(得分:1)
尝试使用自定义xml阅读器和编写器。
public class CustomDateTimeWriter : XmlTextWriter
{
public CustomDateTimeWriter(TextWriter writer) : base(writer) { }
public CustomDateTimeWriter(Stream stream, Encoding encoding) : base(stream, encoding) { }
public CustomDateTimeWriter(string filename, Encoding encoding) : base(filename, encoding) { }
public override void WriteRaw(string data)
{
DateTime dt;
if (DateTime.TryParse(data, out dt))
base.WriteRaw(dt.ToString("u", new CultureInfo("en-US")));
else
base.WriteRaw(data);
}
}
public class CustomDateTimeReader : XmlTextReader
{
public CustomDateTimeReader(TextReader input) : base(input) { }
// define other required constructors
public override string ReadElementString()
{
string data = base.ReadElementString();
DateTime dt;
if (DateTime.TryParse(data, null, DateTimeStyles.AdjustToUniversal, out dt))
return dt.ToString("o");
else
return data;
}
}
使用
var dummy = new Dummy { DummyProperty = DateTime.Now };
Console.WriteLine(dummy.DummyProperty);
var xs = new XmlSerializer(typeof(Dummy));
string xml;
using (var stringWriter = new StringWriter())
using (var xmlWriter = new CustomDateTimeWriter(stringWriter))
{
xmlWriter.Formatting = Formatting.Indented;
xs.Serialize(xmlWriter, dummy);
xml = stringWriter.ToString();
}
Console.WriteLine(xml);
using (var stringReader = new StringReader(xml))
using (var xmlReader = new CustomDateTimeReader(stringReader))
{
dummy = (Dummy)xs.Deserialize(xmlReader);
Console.WriteLine(dummy.DummyProperty);
}
<强>优点:强>
此方法自动(de)将所有日期时间值序列化为所需格式,而无需更改生成的类。
<强>缺点:强>
此方法可能会意外更改日期时间等值。
这种方法可能会减慢(反)序列化的速度。