开发者

Xml serialization. Deserialize and convert to a different object

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)).Seria开发者_开发百科lize(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 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜