Mhr. Cheng,
Thank you very much for your response. Unfortunately I think there's an
error in the .NET framework. Your example works excellent, however there's
one drawback. The xsd type should be xs:date not xs:dateTime. Try to put
your two dates into a class, let's name it CDates. When you XmlSerialize
an instance of this class it still works excellently, i.e. the timezone is
put. Now add the attribute
"[System.Xml.Serialization.XmlAttributeAttribute(DataType="date")]" to
each of the two DateTime fields and try again. Now the timezone is NOT
specified in the xml document.
Doesn't that look as an error in the .NET framework, i.e. it does not put
the timezone when serializing DateTime values decorated with the
attributed mentioned above?
Best regards,
Henrik Dahl
Steven Cheng said:
Hello Henrik,
From your description, you have a custom class(generate from a given XML
schema through xsd tool) that need to be xml serialized. The custom class
contains a DateTime member which will be serialized as an xml attribute.
However, you found the serialized date value is always lack of the
timezone
offset, you're wondering how to force xmlserizer to output timezone
offset,
correct?
Based on my understanding, in .net 2.0, the Datetime class has been
enhanced. first, it support two kinds of DateTime instance
** Local datetime object
**UTC datetime object
this can be specified at the creation time, e.g.
DateTime dt = new DateTime(DateTime.Now.Ticks, DateTimeKind.Local);
And for local DateTime instance, the xmlserlizer will serialize it with
timezone offset included. While for UTC datetime instance, it will not
contain the timezone offset. e.g
the following code snippet will given the output like;
=====code =====
StringWriter sw = new StringWriter();
DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.UtcNow;
XmlSerializer xs = new XmlSerializer(typeof(DateTime));
xs.Serialize(sw, date1);
xs.Serialize(sw, date2);
textBox1.Text = sw.ToString();
sw.Close();
=======================
=========output========
<?xml version="1.0" encoding="utf-16"?>
<dateTime>2006-12-11T21:17:01.7868744+08:00</dateTime><?xml version="1.0"
encoding="utf-16"?>
<dateTime>2006-12-11T13:17:01.7868744Z</dateTime>
=====================
So you can find that if you create a local datetime object, you'll get
the
xmlserlization output with the timezone offset. Do you think it is
possible
that you force your class to hold a local datetime instance?(you can
check
it through DateTime.Kind property)
If this is not doable in your scenario, you may consider create a custom
wrapper class to represent datetime and you can implement our own
XmlSerialization logic through IXmlSerizable interface.
Hope this helps some.
Sincerely,
Steven Cheng
Microsoft MSDN Online Support Lead
This posting is provided "AS IS" with no warranties, and confers no
rights.