时间戳在xml封装期间未写入
本文关键字:xml 封装 时间戳 | 更新日期: 2023-09-27 18:27:33
我正在尝试编写
XmlSerializer xs = new XmlSerializer(object);
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.ASCII);
xs.Serialize(xmlTextWriter, obj);
xmlString = ASCIIByteArrayToString(memoryStream.ToArray())
删除带有时间戳的序列化值之后,为什么?以及如何在c#中序列化时间戳格式值?
有一些事情需要检查。首先是以下行:
XmlSerializer xs = new XmlSerializer(object);
这不是有效的C#,它将不会编译。我想你的意思是:
XmlSerializer xs = new XmlSerializer(obj.GetType());
然后确保Timestamp是该obj的一个属性,该属性具有用于对其进行XML序列化的公共getter和setter。
示例:
public class Foo
{
public DateTime Timestamp { get; set; }
}
然后:
var obj = new Foo
{
Timestamp = DateTime.Now
};
var xs = new XmlSerializer(obj.GetType());
using (var stream = new MemoryStream())
{
xs.Serialize(stream, obj);
string xml = Encoding.UTF8.GetString(stream.ToArray());
}
生产:
<?xml version="1.0"?>
<Foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Timestamp>2012-03-13T08:21:12.5391233+01:00</Timestamp>
</Foo>