将DateTime序列化为时间而不是毫秒和gmt

Esp*_*spo 12 .net time attributes xml-serialization

我使用XSD文件作为输入创建了一个C#类文件.我的一个属性看起来像这样:

 private System.DateTime timeField;

 [System.Xml.Serialization.XmlElementAttribute(DataType="time")]
 public System.DateTime Time {
     get {
         return this.timeField;
     }
     set {
         this.timeField = value;
     }
 }
Run Code Online (Sandbox Code Playgroud)

序列化时,文件的内容现在如下所示:

<Time>14:04:02.1661975+02:00</Time>
Run Code Online (Sandbox Code Playgroud)

在属性上使用XmlAttributes,是否有可能在没有毫秒和GMT值的情况下渲染它?

<Time>14:04:02</Time>
Run Code Online (Sandbox Code Playgroud)

这是可能的,还是我需要在序列化类之后将某种xsl/xpath-replace-magic混合在一起?

它不是将对象更改为String的解决方案,因为它在应用程序的其余部分中像DateTime一样使用,并允许我们使用XmlSerializer.Serialize()方法从对象创建xml表示.

我需要从字段中删除额外信息的原因是接收系统不符合time数据类型的w3c标准.

Mat*_*lls 23

将[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); }
}
Run Code Online (Sandbox Code Playgroud)

  • `"yyyy-MM-dd"`时间字段的正确格式字符串?虽然这个解决方案对我来说不起作用,但确实让我找到了一个.我不得不使用`"HH:mm:ss"`,我从我的`dateField`中获取了这样的`get {return this.dateField.ToString("HH:mm:ss"); }` (2认同)

Jef*_*dge 14

您可以创建一个字符串属性,该属性执行与timeField字段之间的转换,并将序列化属性放在其上,而不是应用程序其余部分使用的实际DateTime属性.