Deserialize XML dateTime to UTC

不打扰是莪最后的温柔 提交于 2019-12-11 06:54:56

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!