代码之家  ›  专栏  ›  技术社区  ›  Gareth maartenba

C#XML反序列化程序未反序列化日期

  •  0
  • Gareth maartenba  · 技术社区  · 6 年前

    我跟你有麻烦 XML 中的反序列化 C# . 我有以下几点 :

    <?xml version="1.0" encoding="utf-8"?>
    <head>
      <person>
        <name>Jim Bob</name>
        <dateOfBirth>1990-01-01</dateOfBirth>
      </person>
      <policy>
        <number>1</number>
        <pet>
          <name>Snuffles</name>
          <dateOfBirth>2000-01-01</dateOfBirth>
        </pet>
      </policy>
    </head>
    

    通过这个,我试图将其映射到以下类:

    public class head
    {
        public policy policy { get; set; }
        public person person { get; set; }
    }
    
    public class person
    {
        public string name { get; set; }
        public DateTime dateOfBirth { get; set; }
    
        [XmlElement("policy")]
        public List<policy> policy { get; set; }
    }
    
    public class policy
    {
        public string number { get; set; }
        [XmlElement("pet")]
        public List<pet> pet { get; set; }
    }
    
    public class pet
    {
        public string name { get; set; }
        [XmlElement("dateOfBirth")]
        public DateTime dateOfBirth { get; set; } //<~~ Issue is with this property
    }
    

    dateOfBirth 房地产 pet 出生日期 房地产 person

    2 回复  |  直到 6 年前
        1
  •  0
  •   jdweng    6 年前

        public class pet
        {
            public string name { get; set; }
            private DateTime _dateOfBirth { get; set; } //<~~ Issue is with this property
    
            [XmlElement("dateOfBirth")]
            public string DateOfBirth
            {
                get { return _dateOfBirth.ToString("yyyy-MM-dd"); }
                set { _dateOfBirth = DateTime.ParseExact(value, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); }
            }
    
    
        }
    
        2
  •  0
  •   Gareth maartenba    6 年前

    我通过使用 [XmlElementAttribute(DataType = "date")] 属性在 dateOfBirth 领域有效的修订类如下所示:

    public class pet
    {
        public string name { get; set; }
        [XmlElementAttribute(DataType = "date")]
        public DateTime dateOfBirth { get; set; }
    }