Deserialising xml with DataContract fails to fill a property

19 Views Asked by At

I am trying to deserialise some XML that we are receiving into objects, however the PubdateMemberString property is always 1/1/0001. I added the member property after it failed to automatically convert the date. Below is a sample C# console program that does just this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace xml_deserialisation_test_c
{
    class Program
    {
        
        public static void Main()
        {
            XElement parameters = XElement.Parse("<Items><SundryItem><BookingKey>X Ref Charge</BookingKey><Dealprice>7500</Dealprice><Quantity>1</Quantity><PubDate>2022-03-26</PubDate></SundryItem><SundryItem><BookingKey>Featured job</BookingKey><Dealprice>39600</Dealprice><Quantity>1</Quantity><PubDate>2022-03-26</PubDate></SundryItem><SundryItem><BookingKey>Email Link</BookingKey><Dealprice>0</Dealprice><Quantity>1</Quantity><PubDate>2022-03-26</PubDate></SundryItem></Items>" );
            var items = GetSundryItems(parameters);
        }

        private static List<SundryItem>GetSundryItems(XElement source)
        {
            var x = new System.Runtime.Serialization.DataContractSerializer(typeof(SundryItem));
            return (from ele in source.Elements()
                    select (SundryItem)x.ReadObject(ele.CreateReader())).ToList();
        }

        [DataContract(Namespace = "", Name = "SundryItem")]
        [Serializable()]
        [System.Xml.Serialization.XmlRoot(ElementName = "SundryItem")]
        public partial class SundryItem
        {
            [DataMember]
            public string BookingKey { get; set; }
            [DataMember]
            public decimal Dealprice { get; set; }
            [DataMember]
            public int Quantity { get; set; }
            [DataMember(Name = "PubDate")]
            public string PubdateMemberString { get; set; }
            [IgnoreDataMember]
            public DateTime PubDate { get; set; }

            [OnSerializing]
            private void OnSerialise(StreamingContext c)
            {
                PubdateMemberString = PubDate.ToString("yyyy-MM-dd");
            }

            [OnDeserialized]
            private void OnDeserialised(StreamingContext c)
            {
                // PubDate = Date.Parse(PubdateMemberString)
            }
        }
    }
}
0

There are 0 best solutions below