gpt4 book ai didi

c# - 在 C# 中序列化没有 GMT 的日期时间

转载 作者:太空宇宙 更新时间:2023-11-03 16:52:52 24 4
gpt4 key购买 nike

我已经从 xsd 生成类并想要序列化 ​​DateTime。我的类(class)看起来像

private System.DateTime timeGMT; 

[System.Xml.Serialization.XmlElementAttribute(DataType="time")]
public System.DateTime TimeGMT {
get {
return this.timeGMT;
}
set {
this.timeGMT= value;
}
}

但是当我分配任何 DateTime 对象时,它的序列化格式为

<TimeGMT>12:00:00.0000000-04:00</TimeGMT>

但我希望它被序列化为

<TimeGMT>12:00:00</TimeGMT>

我看过这个问题:

Serializing DateTime to time without milliseconds and gmt

这和我的情况类似。但我的问题是我还想针对 xsd 验证生成的 xml。所以我无法将返回类型转换为字符串。如果我使用 String 作为返回类型,那么在生成 XML 时会出现异常:

time is an invalid value for XMLElementAttribute.DataType property.The property may be specified for only primitive types.

还有别的出路吗?

最佳答案

您的链接问题中的解决方案是您需要做的。您仍然可以根据 XSD 验证生成的 XML,但 XSD 不应将此元素定义为 XML datetime 类型(因为这是带有毫秒和时区的元素,您说您不想要).相反,您必须定义自己的 XSD 类型来匹配您想要的类型。

关于c# - 在 C# 中序列化没有 GMT 的日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3315457/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com