I've got a simple example that I've boiled down from my real code. The problem is that I can create a C# class below as long as I'm able to explicitly assign the type in the class hierarchy. But, my array of Panels doesn't create a subclassed TwoColumnPanel. Instead, I only get one panel in the list of Panels.
[TestMethod]
public void XmlRepoCreatesTestRepo()
{
object obj;
using (XmlReader reader = XmlReader.Create(new StringReader(TestXml)))
{
reader.MoveToContent();
switch (reader.Name)
{
case "TestRepo":
obj = new XmlSerializer(typeof(TestRepo)).Deserialize(reader);
break;
default:
throw new NotSupportedException("Unexpected: " + reader.Name);
}
}
}
public string TestXml = @"<TestRepo>
<Name>Wandercoder Was Here</Name>
<Page>
<Panel>
<ColumnAttribute>1</ColumnAttribute>
</Panel>
<TwoColumnPanel>
<ColumnAttribute>2</ColumnAttribute>
</TwoColumnPanel>
<Panels>
<Panel>
<ColumnAttribute>1</ColumnAttribute>
</Panel>
<TwoColumnPanel>
<ColumnAttribute>2</ColumnAttribute>
</TwoColumnPanel>
</Panels>
</Page>
</TestRepo>";
}
[DataContract]
[Serializable]
public class TestRepo
{
[DataMember]
public string Name { get; set; }
[DataMember]
public Page Page { get; set; }
}
[DataContract]
[Serializable]
public class Page
{
//This works.
[DataMember]
public Panel Panel { get; set; }
//This works, too.
[DataMember]
public TwoColumnPanel TwoColumnPanel { get; set; }
//For this one, however, I only get the one Panel when I deserialize.
//Why doesn't it properly deserialize the TwoColumnPanel specified in the xml above.
[DataMember]
public List<Panel> Panels { get; set; }
}
[DataContract]
[Serializable]
public class Panel
{
[DataMember]
public int ColumnAttribute { get; set; }
}
[DataContract]
[Serializable]
[XmlRoot("Panel")]
public class TwoColumnPanel : Panel
{
public TwoColumnPanel()
{
ColumnAttribute = 2;
}
}