I deserialize an xml using a lot of serializable objects. I have read that in order to avoid not valid AllXsd value in DateTime, I have to create a helper string property which will handle the input as a string and convert it. i.e.
[XmlIgnore]
public DateTime? DateUpdated { get; set; }
[XmlElement("updateDate")]
public string DateUpdatedAsText
{
set
{
if (!string.IsNullOrWhiteSpace(value))
{
try
{
DateUpdated = DateTime.Parse(value, CultureInfo.InvariantCulture);
}
catch (Exception) { }
}
}
get
{
return DateUpdated.HasValue ? DateUpdated.Value.ToString("yyyy-MM-ddTHH:mm:ss") : null;
}
}
This is tested and works great. However...
I have over 100 entities that contain DateTime fields in them, some of them more than one, and this solution is not very practical. I will have to implement this in all of them and if I want to change anything in the future I will have to do it again in all of them. How can I declare a general custom adapter to handle all DateTime types. In Java I can do this:
@XmlJavaTypeAdapter(CalendarXmlAdapter.class)
@Column(name = "updateDate")
private Calendar DateUpdated;
and in CalendarXmlAdapter.class specify the marshalling and unmarshalling
Is there a similar solution for C# System.Xml.Serialization.XmlSerializer?
Thanks in advance
EDITED
SOLUTION: It is a combination of @dbc comment and @steve16351 answer. I used the CustomDateTime class (with some minor changes in ReadXml, but non important) and in the declaration of the field SomeDate (which remained DateTime? type) I used it like this
[XmlElement(ElementName = "updateDate", IsNullable = true, Type = typeof(CustomDateTime))]
public DateTime? DateUpdated { get; set; }
The convertion takes place smoothly