将 DateTime 序列化为不带毫秒和 gmt 的时间
-
01-07-2019 - |
题
我使用 XSD 文件作为输入创建了一个 C# 类文件。我的其中一个属性如下所示:
private System.DateTime timeField;
[System.Xml.Serialization.XmlElementAttribute(DataType="time")]
public System.DateTime Time {
get {
return this.timeField;
}
set {
this.timeField = value;
}
}
序列化后,文件的内容现在如下所示:
<Time>14:04:02.1661975+02:00</Time>
是否可以通过属性上的 XmlAttributes 使其在没有毫秒和 GMT 值的情况下进行渲染?
<Time>14:04:02</Time>
这是可能的,还是我需要在类序列化后将某种 xsl/xpath-replace-magic 组合在一起?
它不是将对象更改为 String 的解决方案,因为它在应用程序的其余部分中像 DateTime 一样使用,并允许我们使用 XmlSerializer.Serialize() 方法从对象创建 xml 表示形式。
我需要从字段中删除额外信息的原因是接收系统不符合时间数据类型的 w3c 标准。
解决方案
您可以创建一个字符串属性,用于与 timeField 字段进行转换,并将序列化属性放在该属性上,而不是应用程序其余部分使用的真实 DateTime 属性。
其他提示
将 [XmlIgnore] 放在 Time 属性上。
然后添加一个新属性:
[XmlElement(DataType="string",ElementName="Time")]
public String TimeString
{
get { return this.timeField.ToString("yyyy-MM-dd"); }
set { this.timeField = DateTime.ParseExact(value, "yyyy-MM-dd", CultureInfo.InvariantCulture); }
}
不隶属于 StackOverflow