views:

38

answers:

2

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?

+1  A: 

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); }
    }
}
kbrimington
+1, Ok, I have thought about a similar solution but it would require me to modify the tool generated file to add `[XmlIgnore]` to offending property. Even though it is a good one-time solution, it doesn't sound like a good thing when source XSD is often updated with new features. I am thinking it might be best to modify XSD type from `xs:date` to `xs:string` and take it from there.
wpfwannabe
I agree with your analysis. I've run into similar issues due to the format SharePoint expects dates to be. An alternative solution would be to insist the service be more flexible with date formats; however, as you are well aware, this is not always an alternative.
kbrimington
Yet another alternative solution is to roll your own `XmlSerializer`, but I imagine that is more effort than you were looking for.
kbrimington
Probably not. `IXmlSerializable` looks like a better bet even though not too perfect.
wpfwannabe
+1  A: 

I believe implementing IXmlSerializable interface will do a trick. You can then control how you serialize and deserialize your object.

Eric
Sounds promising in terms of being able to plug it in easily with all classes being generated as `partial`. On the other hand, I lose all the good stuff of automatic public property serialization so I must reinvent the wheel. This would not be a problem if the class had just a handful of properties. It has many of them and it sounds like a daunting task to have to maintain this as XSD suffers changes.
wpfwannabe