views:

49

answers:

3

Hi,

I'm xml-serializing a object with a large number of properties and I have two properties with DateTime types. I'd like to format the dates for the serialized output. I don't really want to implement the IXmlSerializable interface and overwrite the serialization for every property. Is there any other way to achieve this?

(I'm using C#, .NET 2)

Thanks.

+1  A: 

You can use a wrapper class/struct for DateTime that overrides ToString method.

public struct CustomDateTime
{
    private readonly DateTime _date;

    public CustomDateTime(DateTime date)
    {
        _date = date;
    }

    public override string ToString()
    {
        return _date.ToString("custom format");
    }
}
Mendy
+5  A: 

For XML serialization you would have to implement IXmlSerializable and not ISerializable.

However you can workaround this by using a helper property and by marking the DateTime properties with the XmlIgnore attribute.

public class Foo
{
    [XmlIgnore]
    public DateTime Bar { get; set; }

    public string BarFormatted
    {
        get { return this.Bar.ToString("dd-MM-yyyy"); }
        set { this.Bar = DateTime.ParseExact(value, "dd-MM-yyyy", null); }
    }
}
João Angelo
Yes,it's IXmlSerializable - was typing in a rush... - corrected. Thanks.
+1  A: 

Check out OXM which is a POCO approach to xml serialization by using a mapping API which gives you an exact control over the generated XML.

Delucia
It looks great, but must use .net2.