0

I have an old XML data file:

<tag1>
  <subtag1>a string</subtag1>
  <subtag2>NIL</subtag2>
  <subtag3>14/06/2023</subtag3>
</tag1>
<tag1>
  <subtag1>another string</subtag1>
  <subtag2>12.33</subtag2>
  <subtag3>NIL</subtag3>
</tag1>
<tag2/>
...

As can be seen, tag2 is recognized as null-valued/empty-valued by the deserializer, hence the single tag. But the first subtag2 and the second subtag3 in my case is also null, but it is either deserialized as a string ("NIL") or exception thrown runtime.

I have attempted this solution for subtag3 DateOnly data type:

[XmlIgnore]
public DateOnly? SomeDates { get; set; }

[XmlElement("subtag3")]
public string? SomeDatesString
{
    get { return SomeDates ?.ToString("dd/MM/yyyy"); }
    set { SomeDates = (value == "NIL" || String.IsNullOrEmpty(value)) ? null : DateOnly.ParseExact(value, "dd/MM/yyyy", CultureInfo.InvariantCulture); }
}

Is there a better, or better yet, optimal best practice solution for recognizing "NIL" as null value?

dbc
  • 104,963
  • 20
  • 228
  • 340
Fariz Awi
  • 43
  • 6
  • 1
    Unfortunately `XmlSerializer` doesn't have this kind of flexibility. See [Deserializing empty xml attribute value into nullable int property using XmlSerializer](https://stackoverflow.com/q/1295697) or [Force XmlSerializer to serialize DateTime as 'YYYY-MM-DD hh:mm:ss'](https://stackoverflow.com/q/3534525) for a similar question, where the answers are to use a surrogate string-valued property (as you are doing) or implement `IXmlSerializable`. – dbc Jun 14 '23 at 16:14
  • I see, thank you for the references too! – Fariz Awi Jun 15 '23 at 21:55

0 Answers0