1

I have 2 derived classes that will be serialized into xml.
While the code works fine (XmlSerializer, nothing strange), the serialization of DataScenario causes its MyData property items to produce Xmlelement names from the base class name:

<DataScenario>
  <MyData>
    <ScenarioData/>
    <ScenarioData/>
    <ScenarioData/>
  </MyData>
<DataScenario>

Instead, i'm trying to have these items produce XmlElement names from their derived classes

<DataScenario>
  <MyData>
    <type1/>
    <type1/>
    <type2/>
  </MyData>
<DataScenario>

Is this even possible? Keep in mind I need to deserialize as well; I'm unsure whether the Deserialize process will understand that derived objects need to be created.

Sample code i'm using is as follows.

[Serializable]
[XmlInclude(typeof(Type1))]
[XmlInclude(typeof(Type2))]
public class Scenario
    {
        [XmlElement("location")]
        public string Location { get; set; }
        [XmlElement("value")]
        public string Value { get; set; }

        public Scenario()
        {
        }
    }

[Serializable]
[XmlType("type1")]
public class Type1 : Scenario
    {
        public FillPointData() : base() { }            
    }


[Serializable]
[XmlType("type2")]
public class Type2 : Scenario
    {
        public TestData() : base() { }            
    }


//Hosting class of all scenarios
public DataScenario()
    {
        public List<Scenario> MyData{ get; set; }
    }
MoSlo
  • 2,780
  • 4
  • 33
  • 37

1 Answers1

4

You can define what kind of Elements are in the Collection with the XmlArrayItem attribute. If the Type is known (defined as you did with the XmlInclude attribute) it will create Tags "Type1", "Type2". If the Types are not known, it will still create a Tag called ScenarioData with an Attribute xsi:type="Type1" which is used to map the type while deserialization.

[XmlArrayItem(typeof(Type1))] 
[XmlArrayItem(typeof(Type2))] 
Public List<Scenario> Children
{
// getter & setter
}
fixagon
  • 5,506
  • 22
  • 26
  • works great! didnt even need the XmlInclude attributes on the base class. – MoSlo Apr 29 '11 at 13:42
  • @MoSlo, Here's another [thread on SO](http://stackoverflow.com/questions/4285242/using-c-xmlserializer-on-derived-classes-while-controlling-the-generated-xml-ele) relevant to this question. – dawebber Apr 29 '11 at 13:43
  • Ok, got a slight deserialization issue. The various types not being identified (list is zero). Is there something with the XmlSerializer I could try for Deserialization? dawebber, the post speaks of a XmlSerializer constructor, but without details. I've tried XmlSerializer(Type,Type[]) without success. – MoSlo Apr 29 '11 at 14:14
  • yes you should use the XmlSerializer(Type,Type[]) constructor with a list of all used types. This doesnt work? – fixagon Apr 29 '11 at 14:18
  • Yup, works. Tried it again, was my fault (was reading the wrong input). – MoSlo Apr 29 '11 at 14:24