问题
I am consuming an XML webservice with XSD elements such as:
<xs:element nillable="true" type="xs:dateTime" name="ENDDATE"/>
XML might look like the following:
<ENDDATE>2016-08-01T18:35:49+04:00</ENDDATE>
I used XSD.exe to autogenerate C# classes, when I inspect these the DateTime
object will contain the time in system-local time, with Kind==Local
.
Is there a way I can force the DateTime instances to be in UTC time without manually hacking the auto-generated classes for every such field (there are rather a lot)?
回答1:
I think that you can't tune this behavior using XSD (see here). So you should update(hack) auto-generated classes and do something like described there:
[XmlIgnore()]
public DateTime Time { get; set; }
[XmlElement(ElementName = "Time")]
public string XmlTime
{
get { return XmlConvert.ToString(Time, XmlDateTimeSerializationMode.RoundtripKind); }
set { Time = DateTimeOffset.Parse(value).DateTime; }
}
Or, if you really often auto-generate those classes, you can introduce wrappers for them, which will transparently convert DateTime to UTC.
来源:https://stackoverflow.com/questions/40091760/deserialize-xml-datetime-to-utc