wpfwannabe wpfwannabe - 9 months ago 61
C# Question

Force XmlSerializer to serialize DateTime as 'YYYY-MM-DD hh:mm:ss'

I have a XSD schema for some RESTful service. When used in conjunction with

tool to generate C# code, XSD's
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
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

If I modify XSD manually to
type, the generated C# code produces:

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?

Answer Source

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
    public DateTime SomeDate { get; set; }

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