序列化后的XML格式的UTC时间

时间:2018-03-08 15:32:19

标签: c# xml-serialization xmlserializer xml-attribute

我有以下XSD定义:

public class Test
{
    private System.DateTime time;

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

我现在有以下代码:

        var p = new Test
        {                
            Time = DateTime.UtcNow
        };

        var xml = ToXml(p);

        Console.WriteLine(xml);

        Console.ReadLine();

以下序列化xml:

    public static string ToXml(Test value)
    {
        var settings = new XmlWriterSettings();
        settings.Encoding = new UnicodeEncoding(false, false);
        settings.Indent = false;
        settings.OmitXmlDeclaration = true;

        using (var textWriter = new StringWriter())
        {
            using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
                new XmlSerializer(typeof(Test)).Serialize(xmlWriter, value);

            return textWriter.ToString();
        }
    }

上面的代码输出时间如下:

<Time>15:24:43.2588160+00:00</Time>

我想用UTC格式。 e.g。

<Time>15:24:43.00Z</Time>

我怎样才能做到这一点?

我无法控制XSD,但如果需要,我可以更改Serializer方法。

与此问题非常相似,但我无法编辑XSD:

Serializing DateTime to time without milliseconds and gmt

1 个答案:

答案 0 :(得分:0)

一种方法是[XmlIgnore]你的DateTime属性,并有一个单独的字符串属性,它将以你指定的格式输出/输入时间。

[XmlIgnore]
public System.DateTime Time
{
    get { return this.time; }
    set { this.time = value; }
}

[System.Xml.Serialization.XmlElementAttribute(DataType = "time")]
public string TimeString 
{
    get { return Time.ToString("yyyy-MM-dd"); }
    set { Time = DateTime.Parse(value); }
}