Blog First. Ask Questions Later.
If you've tried to XML serialize a System.TimeSpan value, you may have noticed that your node is null, no matter what you set the TimeSpan value to be. There's a nice workaround to this posted here by Ben Lucas. Basically, you [XmlIgnore] your object's TimeSpan property, and add another that serializes the time span's ticks. Pretty simple, but works great!
[XmlIgnore]
public System.TimeSpan TimeToBeReceived
{
get { return timeToBeReceived;}
set
{
if (timeToBeReceived == value) return;
timeToBeReceived = value;
}
}
public long TimeToBeReceivedTicks
{
get { return timeToBeReceived.Ticks; }
set { this.timeToBeReceived = new TimeSpan(value); }
}
So instead of this:
<TimeToBeReceived />
You get this:
<TimeToBeReceivedTicks>864000000000</TimeToBeReceivedTicks>
Thanks Ben!
-Brendan
About Brendan Tompkins
Brendan has been programming with .NET since the first public beta and is owner and operator of Port Technology Services, a consultancy company providing .NET application development services to the Maritime industry. In July, 2007, he was awarded the Microsoft MVP award for ASP.NET.
He's also a proud co-founder of failed .COM startup Intrinsigo, and has had a hand in the failure of numerous other businesses.
He currently runs CodeBetter.Com and Devlicio.us, and lives in Norfolk, Virgina with his wife Tiara and son Ian.