I have class:
public class MyClass
{
[XmlElement("Date")]
public DateTime Date { get; set; }
}
It was XML serialized to a file:
var myClass = new MyClass() { Date = new DateTime(2010, 09, 24) };
new XmlSerializer(typeof(MyClass)).Serialize(fileStream, myClass);
The result:
<MyClass>
<Date>2010-09-24T00:00:00</Date>
</MyClass>
After that the new date-holder class was created:
public class MyDate
{
public int Year { get; set; }
public int Month { get; set; }
public int Date { get; set; }
}
And was used in MyClass instead of System.DateTime:
public class MyClass
{
[XmlElement("Date")]
public MyDate Date { get; set; }
}
What I need is to make following code work fine:
MyClass myClass = (MyClass)new XmlSerializer(typeof(MyClass)).Deserialize(fileStream);
The problem is I can’t change the MyClass. The only things I can change are MyDate class and serialization/deserialization code.
How to make the deserialization code so as new class MyDate is deserialized from previously serialized System.DateTime?
One option would be to implement
IXmlSerializableon theMyDateclass and then parse the date string in theReadXmlmethod usingXmlConvert.ToDateTime.If the purpose of the
MyDateclass is to have a different XML format, then you could support both input formats in theReadXmlmethod by checking what is actually present in the element, but always write to the new format in theWriteXmlmethod.