1

In this example which uses a C# record rather than a class, the XmlAttribute attribute is ignored when serializing using the standard XmlSerializer. Why is this?

public record Person (
    string Name,
        
    [XmlAttribute("dte_created")]
    DateTime CreatedAt
) {
    // parameterless ctor required for xml serializer
    public Person() : this(null, DateTime.MinValue) {}
};
Mr Grok
  • 3,876
  • 5
  • 31
  • 40

2 Answers2

3

In your code, you are setting the attribute to the constructor argument

public record Person([XmlAttribute("dte_created")]DateTime CreatedAt);

You need to instruct the compiler to set the attribute on the property using property::

public record Person([property: XmlAttribute("dte_created")]DateTime CreatedAt);
meziantou
  • 20,589
  • 7
  • 64
  • 83
1

The problem is that I'm using the positional syntax for defining the record and the generated auto-property is not aware of the XmlAttribute. However, I could achieve the same effect by explicitly stating how the property was to be generated. Like this:

public record Person (string Name, DateTime CreatedAt) {
    [XmlAttribute("dte_created")]
    public DateTime CreatedAt { get; init; } = CreatedAt;

    // parameterless ctor required for xml serializer
    public Person() : this(null, DateTime.MinValue) {}
}
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
Mr Grok
  • 3,876
  • 5
  • 31
  • 40