Want to show your appreciation?
Please a cup of tea.

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); }
}

10 comments:

baz said...

great!

is this still required in .NET 3.5? It seems that TimeSpan is not yet managed.. :(

Damir Arh said...

It's still required even in .NET 4.

Unknown said...

and... 2.5 years later in 2013 this is STILL required. Come on Microsoft.

Anonymous said...

and ... 4 months later in 2013 this workaround does not even work on Windows Phone 8.

Anonymous said...

We write the year 2014 (30.10.2014) and its still required!

Anonymous said...

happy new year 2015!!! still nothing...

Anonymous said...

this is ridicolous in 2018

avvilibber28 said...

You should participate in a contest for top-of-the-line blogs on the web. I will suggest this site! online casinos for us players

sandilau said...

Same in 2020. No implementation for xml serialization :(

Unknown said...

원주콜걸
삼척콜걸
이천콜걸
성주콜걸
이천콜걸
춘천콜걸
칠곡콜걸

Post a Comment