XmlSerializer question

  • Thread starter Thread starter The Last Danish Pastry
  • Start date Start date
T

The Last Danish Pastry

Why is it that I can serialize a DateTime using XmlSerializer, but not
a TimeSpan?

Also, and perhaps more importantly - how could I have known ahead of
time, using the published documentation, that DateTime is going to
work and TimeSpan isn't?

Trying to serialize a TimeSpan does not throw any exceptions or
trigger any events.
 
Hi,

According to MSDN TimeSpan does support serialization, what errors are you
seeing?
Could you post some code?
 
Hi,

According to MSDN TimeSpan does support serialization, what errors
are you seeing?
Could you post some code?

Hi. And thanks for your swift response.

Here is some code that produces two files of xml.

c:\qaz\DateTime.xml can be used to correctly deserialize the original
DateTime object.

c:\qaz\TimeSpan.xml has no information about the TimeSpan object,
which thus cannot be deserialized.

Code...
=========================================

private void button1_Click(object sender, EventArgs e)
{
{
const string fileName = @"c:\qaz\DateTime.xml";
DateTime testObject = new DateTime(2000, 12, 25, 1, 2, 3);
XmlSerializer xs = new XmlSerializer(testObject.GetType());
StreamWriter sw = new StreamWriter(fileName);
xs.Serialize(sw, testObject);
sw.Close();
}
{
const string fileName = @"c:\qaz\TimeSpan.xml";
testObject = new TimeSpan(1, 2, 3, 4, 5);
XmlSerializer xs = new XmlSerializer(testObject.GetType());
StreamWriter sw = new StreamWriter(fileName);
xs.Serialize(sw, testObject);
sw.Close();
}
} // button1_Click

=========================================

c:\qaz\DateTime.xml...
=========================================
<?xml version="1.0" encoding="utf-8"?>
<dateTime>2000-12-25T01:02:03</dateTime>
=========================================

c:\qaz\TimeSpan.xm...
=========================================
<?xml version="1.0" encoding="utf-8"?>
<TimeSpan xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" />
=========================================
 
Hi. And thanks for your swift response.

Here is some code that produces two files of xml.

c:\qaz\DateTime.xml can be used to correctly deserialize the
original DateTime object.

c:\qaz\TimeSpan.xml has no information about the TimeSpan object,
which thus cannot be deserialized.

Code...
=========================================

private void button1_Click(object sender, EventArgs e)
{
{
const string fileName = @"c:\qaz\DateTime.xml";
DateTime testObject = new DateTime(2000, 12, 25, 1, 2, 3);
XmlSerializer xs = new XmlSerializer(testObject.GetType());
StreamWriter sw = new StreamWriter(fileName);
xs.Serialize(sw, testObject);
sw.Close();
}
{
const string fileName = @"c:\qaz\TimeSpan.xml";
testObject = new TimeSpan(1, 2, 3, 4, 5);


Oops, that line should be...
 
Back
Top