我是一名编程专业的学生,我想知道在将日期序列化为 xml 文件时是否可以更改日期格式。这个日期是对象“Loan”的 ObservableCollection 的一个属性,这个对象有两个 DateTime 属性,其中一个日期是一个可以为 null 的对象。我序列化了所有系列,包括日期。
我想在xml文件中获取:
<OutDate> 15-03-2014 </OutDate>
<!--If the date is null I don´t want to appear the node-->
我明白了:
<OutDate>2014-03-15T00:00:00</OutDate>
<InDate xsi:nil="true" />
这是我的代码项目的一部分: 我的 Loan 类的一部分,已经标记为可序列化,如下所示:
private string isbn;
private string dni;
private DateTime dateOut;
private DateTime? dateIn;
// Setters and Gettters and constructors
这是序列化的方法:
// I will pass three collections to this method loans, books and clients
public void SerializeToXML<T>(string file, string node, ObservableCollection<T> collection)
{
XmlRootAttribute root = new XmlRootAttribute(node);
XmlSerializer serializer = new XmlSerializer(typeof(ObservableCollection<T>), root);
using (FileStream fs = new FileStream(file, FileMode.Create))
{
serializer.Serialize(fs, collection);
}
}
电话:
SerializeToXML<Loan>(_file, "Library", manager.LoansCollection);
谢谢。
最佳答案
如果你不想执行IXmlSerializable ,一些 DateTime 到支持字段的字符串转换应该可以解决问题,如下所示:
public class Loan
{
[XmlIgnore]
private DateTime _dateOut;
public string OutDate
{
get { return _dateOut.ToString("dd-MM-yyyy"); }
set { _dateOut = DateTime.Parse(value); }
}
}
关于c# - 在 C# 中将 DateTime 属性序列化为 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22220542/