I’ve got this XML:
<price currency="EUR">123.45</price>
I want to deserialise that onto a class with Currency
and Value
properties.
However, when I do that, I get an error about how [XmlText]
has to be a string.
So, I’ve written this which lets me deserialise it:
[XmlRoot("price")]
public class Price
{
[XmlAttribute("currency")]
public string? Currency { get; init; }
// Needed because you can't have a decimal in an XML element apparently
// Unfortunately, that means I have to expose this
[XmlText]
public string? RawValue { private get; set; }
[XmlIgnore]
public decimal? Value
{
get => decimal.TryParse(RawValue, out decimal value) ? value : null;
set => RawValue = value?.ToString(CultureInfo.InvariantCulture);
}
}
Which I hate for obvious reasons.
Is there any way around this?