XmlSerializer and TimeSpan don't get along
While I was implementing the data import/export functionalities of MotoX Stopwatch, having decided to use the XmlSerializer to load and save human readable files, I found out that the serializer doesn't work for TimeSpan values for some reason! ![]()
It appears to be a known problem and several other people have already posted their workarounds. However, here's my solution using Cobra: mark the TimeSpan properties (which cannot be serialized normally) with the XmlIgnore attriute. This will force the serializer to skip them. Then declare new string properties, which you will never use in your code, that simply wrap the original TimeSpan value.
use System.Xml
use System.Xml.Serialization
class StopWatchInfo
has Serializable
# ... normal properties ...
# The next property will be ignored by the serializer
var time as TimeSpan
is public
has XmlIgnore
# This property wraps the one above for the serializer
pro timeWrap as String
get
return .time.toString
set
ret = TimeSpan()
if TimeSpan.tryParse(value, out ret)
.time = ret
else
.time = TimeSpan.zero
Remember that the serializer uses the property names of the class, therefore "timeWrap" will appear in the output file instead of "time". To avoid this, you'll want to rename the wrapping property adding an XmlAttribute to it.



