views:

479

answers:

3

Is there any way I can define how a DateTime should be serialized/deserialized using something similar to the XmlAttribute tag? In the past I would make the field a string and then do something like this in the constructor:

this.DateField = XmlConvert.ToString(passedObject.Date, XmlDateTimeSerializationMode.Utc);

However, I'd like to actually have the field be a DateTime and somehow tag that it should be serialized as UTC:

[System.Xml.Serialization.XmlAttribute()] // XmlDateTimeSerializationMode tag here?
public DateTime DateField;

How would I do that?

+1  A: 

I'm not sure you can do it via attributes, as your crossing the line from serializing your data as it is, to transforming it and then serializing.

You could perhaps get the same result by changing the way you represent the data, by adding a UTC protected property, i.e:

public DateTime DateField;

[System.Xml.Serialization.XmlAttribute("DateField")]
protected DateTime UtcDateField
{
    get
    {
        //Convert DateField to UTC
    }

    set
    {
        DateField = //Convert value from UTC
    }
}
MattH
Thanks Matt! I actually ended up having to add an XmlIgnore attribute to the real DateField or else it would serialize it as an element.
Brandon
A: 

Another option is to inherit the IXmlSerializable interface and handle all the reading and writing of your serialization manually. It's not as succinct or automatic as attributes but it will give you the control you need and I think it's easier to understand than creating special formatted fields just for the serialization process.

Spencer Ruport
A: 

XMLIgnore seems to be the way to go. I was having the same issue. Thanks!

RCavallaro