This question is about re-factoring an XMl model that works for XML I receive but can't alter - although the names have changed.
I have the following classes:
[XmlType(AnonymousType = true)]
[XmlRoot(ElementName = "loadsOfMainType", Namespace = "", IsNullable = false)]
class MainType
{
[XmlElement("mainType")]
public MyNameForMainType[] MainTypes { get; set; }
}
[XmlRoot(ElementName = "aMainType", Namespace = "", IsNullable = false)]
[XmlType(AnonymousType = true)]
public class MyNameForMainType
{
[XmlElement("single")]
public Single Single { get; set; }
[XmlElement("dual")]
public Dual Dual { get; set; }
}
[XmlType(AnonymousType = true)]
public class Single
{
[XmlElement("thing1")]
public Thing1 MyNameForThing1 { get; set; }
[XmlElement("thing2")]
public Thing2 MyNameForThing2 { get; set; }
[XmlElement("thing3")]
public Thing3 MyNameForThing3 { get; set; }
[XmlElement("somthingElseInSingle")]
public StuffInSingleOnly StuffInSingle { get; set; }
}
[XmlType(AnonymousType = true)]
public class Dual
{
[XmlElement("thing1")]
public Thing1 MyNameForThing1 { get; set; }
[XmlElement("thing2")]
public Thing2 MyNameForThing2 { get; set; }
[XmlElement("thing3")]
public Thing3 MyNameForThing3 { get; set; }
[XmlElement("someStuffInDual")]
public StuffInDualOnly StuffInDual { get; set; }
}
As you can see, Thing1, Thing2, Thing3 are all candidates for moving to another class. There are other classes that will benefit from the same re-factor.
I want to create a class for those "Thing"s and have the XMLSerializer take my MainType with the new type under Single or Dual - let's call it CommonThing such that, for instance, Single would become:
[XmlType(AnonymousType = true)]
public class Single
{
public CommonThing CommonThing { get; set; }
[XmlElement("somthingElseInSingle")]
public StuffInSingleOnly StuffInSingle { get; set; }
}
I've tried all sorts of XML serialization decorations on CommonThing, both in Single, and in CommonThing, and for the life of me the best I can get is CommonThing coming back as null.
Is there some combination of attributes I can add in either or both of Single and CommonThing that will work (or even MainType)?
Please note that I am only passing MainType as my T into a ReadAsAsync because I have other T's that don't want to use CommonThing (although I guess I could pass another type as I wrote that bit and I reckon it would get ignored for T's without CommonThing - but I don't think I really should need to).