Just had to figure this out and thought I’d share. With the XmlSerializer (.NET v1.1), one would think that TimeSpan maps to the XML Schema type duration, but it doesn’t – for whatever reason. Anyways … here’s a trick to make it work. Interestingly enough, the XmlConvert class understands TimeSpan. However it does not work correctly with fractional seconds and ignores them. That’s enough for my purposes in the given app and therefore I am ignoring that issue in the snippet below and treat all times of less than one second as equivalent to zero. If it isn’t enough for you, you’d have to write an alternate implementation for the respective XmlConvert functionality or beg Microsoft to fix it. (Doug? ;-)

 

private TimeSpan interval;

[XmlElement("Interval", DataType="duration")]
public string IntervalXml
{
    get
    {
        if (Interval < TimeSpan.FromSeconds(1) )
        {
            return null;
        }
        else
        {
            return XmlConvert.ToString(interval);
        }
    }
    set
    {
        if (value == null )
        {
            interval = TimeSpan.Zero;
            return;
        }
        TimeSpan newInterval = XmlConvert.ToTimeSpan(value);
        if (interval == newInterval)
            return;
        interval = newInterval;
    }
}

[XmlIgnore]
public TimeSpan Interval
{
    get
    {
        return interval;
    }
    set
    {
        if (interval == value)
            return;
        interval = value;
    }
}

 

 

Updated: