简体   繁体   English

如何在C#中将XML日期值序列化为DateTime类

[英]How to serialize xml date value to DateTime class in c#

I am passing the following xml 我正在传递以下xml

<PolicyNumber>6456365A1</PolicyNumber>
<EffectiveDate>2015-10-01T00:00:00</EffectiveDate>
<ExpirationDate>2016-10-01T00:00:00</ExpirationDate>

to class through fiddler post.But the Values in the following class 通过小提琴手课上课。但以下课中的价值观

    [DataContract]
    public class Parameter
    {
        [DataMember]
        public string PolicyNumber { get; set; }
        [DataMember] 
        public DateTime EffectiveDate { get; set; }
        [DataMember]
        public DateTime ExpirationDate { get; set; }
    }

The value for policy number getting passed as expected.The value for DateTime is not getting passed instead it has its default value. 策略编号的值按预期方式传递。DateTime的值未传递,而是具有其默认值。 I am posting it using fiddler to web api mvc. 我正在使用提琴手将其发布到Web api mvc。

在此处输入图片说明

You can simply make it a private member that is only used for serialization. 您可以简单地将其设为仅用于序列化的私有成员。

[DataContract]
public class AutoIDCardParameter
{
    [DataMember(Name = "PolicyNumber")]
    public string PolicyNumber;

    [DataMember(Name = "EffectiveDate")]
    private string _EffectiveDate {
        get {
            return EffectiveDate.ToString("yyyy-MM-DDTHH:mm:ss");
        }
        set {
            DateTime.TryParse(value, out EffectiveDate);
        }
    }

    public DateTime EffectiveDate;

    // ....
}

The order is wrong here. 这里的顺序是错误的。 DataContractSerializer will use alphabetical order unless you specify otherwise (see the docs ), so it's expecting EffectiveDate , ExpirationDate , and then PolicyNumber . 除非您另外指定(请参阅docs ),否则DataContractSerializer将使用字母顺序,因此,它期望的是EffectiveDateExpirationDate ,然后是PolicyNumber

You need to either re-arrange your XML to be in that order, or you need to specify the order on the class via attributes: 您需要将XML重新排列为该顺序,或者需要通过属性在类上指定顺序:

[DataContract]
public class Parameter
{
    [DataMember(Order = 0)]
    public string PolicyNumber { get; set; }
    [DataMember(Order = 1)]
    public DateTime EffectiveDate { get; set; }
    [DataMember(Order = 2)]
    public DateTime ExpirationDate { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM