Want to show your appreciation?
Please a cup of tea.
Showing posts with label XmlSerializer. Show all posts
Showing posts with label XmlSerializer. Show all posts

Wednesday, September 24, 2008

XmlSerializer Doesn't Serialize TimeSpan to XML Duration Type

Somebody said this is by design. Then this is another design flaw and evidence of the immaturity of .Net Framework?! Google for "convert XML duration type to TimeSpan" returned all kind of workarounds. The general idea is to use a helper string property to make the Dumb XmlSerializer happy. But some of them are just inappropriate due to the way the TimeSpan is converted to string. XML Schema type xs:duration has its special format. This one simply uses TimeSpan.ToString(). There is also a book presented a home grown utility to do the conversion. While XmlSerializer failed to handle it, but it is ironical that there is a .Net Framework class, XmlConvert, does exactly this but sadly, the designer of XmlSerializer simply ignored it.

Below is the workaround I used to map the TimeSpan to xs:duration.

private TimeSpan _timeToLive = new TimeSpan(0, 10, 0); // 10 minutes
 
[XmlIgnore]
public TimeSpan TimeToLive
{
    get { return _timeToLive; }
    set { _timeToLive = value; _expiration = null; }
}
 
[XmlAttribute("TimeToLive", DataType = "duration")]
[DefaultValue("PT10M")]
public string XmlTimeToLive
{
    get { return XmlConvert.ToString(_timeToLive); }
    set { _timeToLive = XmlConvert.ToTimeSpan(value); }
}