代码之家  ›  专栏  ›  技术社区  ›  Espo

将DateTime序列化为没有毫秒和gmt的时间

  •  12
  • Espo  · 技术社区  · 17 年前

    我使用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替换魔术?

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

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

    2 回复  |  直到 17 年前
        1
  •  24
  •   Matt Howells    15 年前

    在Time属性上添加[XmlIgnore]。

    然后添加一个新属性:

    [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); }
    }
    
        2
  •  14
  •   Jeffrey L Whitledge    17 年前

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

    推荐文章