I\'m having trouble trying to customize the way DateTime variables are serialized in my objects. I want it to be output as 2011-09-26T13:00:00Z but when I override the GetOb
You're trying to customize standard serialization (ISerializable) for a property type whose containing type is being serialized with XmlSerializer. You need implement the IXmlSerializable interface to customize XML Serialization. Try something like this:
public class gdEvent : IXmlSerializable
{
private DateTime _startTime;
private DateTime _endTime;
public gdEvent(DateTime startTime, DateTime endTime)
{
_startTime = startTime;
_endTime = endTime;
}
public gdEvent()
{
_startTime = DateTime.MinValue;
_endTime = DateTime.MinValue;
}
public XmlSchema GetSchema()
{
return null;
}
public void WriteXml(XmlWriter writer)
{
if (_startTime != DateTime.MinValue)
writer.WriteAttributeString("startTime", _startTime.ToString("yyyy-MM-ddTHH:mm:ssZ"));
if (_endTime != DateTime.MinValue)
writer.WriteAttributeString("endTime", _endTime.ToString("yyyy-MM-ddTHH:mm:ssZ"));
}
public void ReadXml(XmlReader reader)
{
string startTimeString = reader.GetAttribute("startTime");
if (!string.IsNullOrEmpty(startTimeString))
{
_startTime = DateTime.Parse(startTimeString);
}
string endTimeString = reader.GetAttribute("startTime");
if (!string.IsNullOrEmpty(endTimeString))
{
_endTime = DateTime.Parse(endTimeString);
}
}
}
I had a suggestion from @craighawker to format the DateTime into a string when calling a set() method for the DateTime. Seemed the simplest method although I would like to implement it the proper way using IXMLSerializable at some point in the future to do more powerful things
public class gdEvent
{
[XmlAttribute(AttributeName = "startTime")]
private string m_startTimeOutput;
private DateTime m_startTime; //format 2011-11-02T09:00:00Z
[XmlAttribute(AttributeName = "endTime")]
private string m_endTimeOutput;
private DateTime m_endTime; //2011-11-02T10:00:00Z
public DateTime startTime
{
get
{
return m_startTime;
}
set
{
m_startTime = value;
m_startTimeOutput = m_startTime.ToString("yyyy-MM-ddTHH:mm:ssZ");
}
}
public DateTime endTime
{
get
{
return m_endTime;
}
set
{
m_endTime = value;
m_endTimeOutput = m_endTime.ToString("yyyy-MM-ddTHH:mm:ssZ");
}
}