0

Here's the situation: I have the following ProjectDto class that I would like to serialize / deserialize:

[XmlRoot(ElementName = "Project", Namespace = "My.Special.Namespace")]
public class ProjectDto
{
  [XmlArrayItem("MyEntry")]
  public List<MyEntryDto> MyEntries { get; } = new List<MyEntryDto>();
}

When I serialize this class, my MyEntryDto objects are listed as <MyEntry> fields in the output xml.

For some reason, I need to introduce a new xml field name for that <MyEntry> field. I need to output those fields as <MyEntryV2> from today on, but I still need to be able to read in files containing the old <MyEntry> field. I don't need to be able to read xml files mixing the two entries though. I will read xml files containing either only <MyEntry> fields or only <MyEntryV2> fields.

My initial guess was that something like

[XmlRoot(ElementName = "Project", Namespace = "My.Special.Namespace")]
public class ProjectDto
{
  [XmlIgnore]
  public EntryType[] MyEntryTypes;

  [XmlChoiceIdentifier("MyEntryTypes")]
  [XmlArrayItem("MyEntry")]
  [XmlArrayItem("MyEntryV2")]
  public List<MyEntryDto> MyEntries { get; } = new List<MyEntryDto>();
}

[XmlType(IncludeInSchema = false)]
public enum EntryType
{
  MyEntry,

  MyEntryV2
}

would do the trick, but at runtime I get a complaint that both MyEntry and MyEntryV2 have the same type, therefore the XmlSerializer can't deal with ProjectDto.MyEntries. In the end, mapping different xml array item names to the same c# data object is what I want to do. My data object will just have all the fields of all the data structures I want to support. I need to read all supported xml array item names (MyEntry, MyEntryV2) but only serialize as MyEntryV2.

How can I achieve that? I've seen this possibility but I find it complicated. Is there something easier?

Laurent Michel
  • 939
  • 1
  • 11
  • 24
  • I think in such a case you may switch to [Linq2XML](https://docs.microsoft.com/en-us/dotnet/standard/linq/linq-xml-overview) intead of serializing. There you have better control about reading/writing – dba Aug 26 '21 at 08:27

0 Answers0