强制XmlSerializer的以日期时间序列为'YYYY-MM-DD HH:MM:SS“ [英] Force XmlSerializer to serialize DateTime as 'YYYY-MM-DD hh:mm:ss'

查看:830
本文介绍了强制XmlSerializer的以日期时间序列为'YYYY-MM-DD HH:MM:SS“的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些RESTful服务XSD模式。当与 XSD.EXE 使用的工具来生成C#code,XSD的的xs:日期生成以下code:

<$p$p><$c$c>[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified,数据类型=日)] 公共System.DateTime的时间{     得到 {         返回this.timeField;     }     组 {         this.timeField =价值;     } }

在使用的XmlSerializer 一切似乎很好地反序列化的XML对象。我现在面临的问题是,该服务预计日期被格式化为 YYYY-MM-DD HH:MM:SS 和XSD生成code似乎只对生产 YYYY-MM-DD

如果我手动修改XSD以的xs:日期时间输入,生成的C#code生产: 2010-08-20T20:07: 03.915039Z

基本上,我怎么逼系列化生产 YYYY-MM-DD HH:MM:SS ?有什么做的XSD或者是有什么我可以做的修改生成的C#code?

解决方案

在过去,我已经做了以下控制日期时间序列化:

  • 忽略日期时间属性。
  • 创建一个虚拟字符串属性,序列化/反序列化的方式我想

下面是一个例子:

 公共类SomeClass的
{
    [XmlIgnore]
    公开日期时间SomeDate {获得;组; }

    [的XmlElement(SomeDate)]
    公共字符串SomeDateString
    {
        {返回this.SomeDate.ToString(YYYY-MM-DD HH:MM:SS); }
        集合{this.SomeDate = DateTime.Parse(值); }
    }
}
 

I have a XSD schema for some RESTful service. When used in conjunction with xsd.exe tool to generate C# code, XSD's xs:date generates the following code:

[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, DataType="date")]
public System.DateTime time {
    get {
        return this.timeField;
    }
    set {
        this.timeField = value;
    }
}

When deserializing XML to objects using XmlSerializer all seems to be well. The problem I am facing is that the service expects dates to be formatted as YYYY-MM-DD hh:mm:ss and the XSD generated code seems to produce only YYYY-MM-DD.

If I modify XSD manually to xs:dateTime type, the generated C# code produces: 2010-08-20T20:07:03.915039Z.

Basically, how do I force serialization to produce YYYY-MM-DD hh:mm:ss? Is there something to do to XSD or is there something I can do to alter generated C# code?

解决方案

In the past, I've done the following to control datetime serialization:

  • Ignore the DateTime property.
  • Create a dummy string property that serializes/deserializes the way I want

Here is an example:

public class SomeClass
{
    [XmlIgnore]
    public DateTime SomeDate { get; set; }

    [XmlElement("SomeDate")]
    public string SomeDateString
    {
        get { return this.SomeDate.ToString("yyyy-MM-dd HH:mm:ss"); }
        set { this.SomeDate = DateTime.Parse(value); }
    }
}

这篇关于强制XmlSerializer的以日期时间序列为'YYYY-MM-DD HH:MM:SS“的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆