views:

19

answers:

1

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?

A: 

One option would be to implement IXmlSerializable on the MyDate class and then parse the date string in the ReadXml method using XmlConvert.ToDateTime.

If the purpose of the MyDate class is to have a different XML format, then you could support both input formats in the ReadXml method by checking what is actually present in the element, but always write to the new format in the WriteXml method.

Greg Beech
IXmlSerializable.ReadXml is never invoked. I dunno why. Any ideas?
Vasiliy Borovyak
If you've implemented it on the `MyDate` type it should always be invoked by the serializer... No idea why it wouldn't be I'm afraid, it has always worked in the past when I've used it.
Greg Beech