1

I would like serialize object to XML. This part is easy. But i would serialize properties (like DateTime) with a specific format.

My current code is this one :

[XmlIgnore]
    private DateTime _paymentDate { get; set; }

    public string PaymentDate
    {
        get
        {
            return this._paymentDate.ToString("yyyy-MM-dd HH:mm:ss");
        }
        set
        {
            this._paymentDate = DateTime.ParseExact(value, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
        }
    }

But it's very bad. If i have 100 DateTime properties, i should duplicate this code 100 times.

So, i would like to use a formatter (like with Newtonsoft JSON). How can i do it ?

Thanks a lot :)

OtakuSan
  • 33
  • 4
  • A similar problem as [here](https://stackoverflow.com/q/22364889/9695604). The accepted answer is the right direction but very incomplete, you will see. – bommelding Jan 21 '19 at 14:38
  • @bommelding - Last time I checked, `XmlSerializer` doesn't call `XmlWriter.WriteValue(DateTime)`, it formats the `DateTime` string itself and calls `XmlWriter.WriteValue(string)`. So overriding the `XmlWriter` method didn't work when I last looked into it. – dbc Jan 21 '19 at 20:37
  • You would like to replace all `DateTime` objects with a custom-serialized surrogate, but `XmlSerializer` doesn't really support surrogate injection. The closest you can get is the neat trick from [Most elegant XML serialization of Color structure](https://stackoverflow.com/a/4322461) - but unfortunately that doesn't work for primitives, and `DateTime` is a primitive. See https://dotnetfiddle.net/V56Yvt, which fails. – dbc Jan 21 '19 at 20:39
  • Now oddly enough `DateTime?` (nullable datetime) is considered a primitive on some .Net versions, but not others! Here you can see the trick working on .Net core: https://dotnetfiddle.net/c6F7Ws and failing on .Net 4.5: https://dotnetfiddle.net/Nxfeov. Related: [C# XmlSerializer - Generic custom adapter to handle not valid AllXsd value (like java's XmlJavaTypeAdapter)](https://stackoverflow.com/q/52702216). – dbc Jan 21 '19 at 20:40

0 Answers0