c# - 在 C# 中将 DateTime 属性序列化为 XML

标签 c# xml c#-4.0 datetime serialization

我是一名编程专业的学生,​​我想知道在将日期序列化为 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/

相关文章:

c# - 如何在我的所有属性(property)中使用 “distinct”

java - xml 节点上的 getTextContent 返回空指针异常

xml - 使excel导出多个XML文件中的每一行

Android无法正常打开activity_main.xml

c# - 如果 Controller 与 View 强绑定(bind),为什么 Controller 需要模型参数?

NHibernate 投影 (QueryOver.SelectList) 限制

c# - Xamarin/C# 中的 Android FileObserver 示例?

c# - 如何先用EF代码通过where子句查询

c# - 如何打开另一个应用程序的配置文件

c# - 使用 Visual Studio 速成版有什么缺点?