title: C# XML List of Multiple Types
body: <p>I am pulling some data from a 3rd party web service that is very complex.  The XSD tool doesn't work on the particular schema so I am attempting to manually build all the data objects.</p>
  
  <pre><code>&lt;Children&gt;
      &lt;Activity&gt;&lt;/Activity&gt;
      &lt;Activity&gt;&lt;/Activity&gt;
      &lt;Container&gt;&lt;/Container&gt;
      &lt;Activity&gt;&lt;/Activity&gt;
      &lt;Container&gt;&lt;/Container&gt;
      ...
  &lt;/Children&gt;
  </code></pre>
  
  <p>Essentially each item in the Collection can either be an Activity or a Container but not both.</p>
  
  <p>I am attempting to use the XmlSerializer in C# to Serialize/Deserialize the Xml and I have an object library backing the Serializer that currently looks like so:</p>
  
  <pre><code>[XmlType(AnonymousType = true)]
  public class Children: XmlEntityBase, IChildren
  {
   [XmlElement("Children", IsNullable = false)]
   public List&lt;ChildrenItems&gt; ChildrenItems { get; } = new List&lt;ChildrenItems&gt;();
  }
  
  [XmlType(AnonymousType = true)]
  public class ChildrenItem: XmlEntityChoice, IChildrenItem
  {
   [NotMapped]
   [XmlElement(nameof(Activity), Type = typeof(Activity), IsNullable = false)]
   [XmlElement(nameof(Container), Type = typeof(Container), IsNullable = false)]
   public object SelectedValue
   {
    get { return _selectedValue; }
    set 
    { 
     if(_selectedValue == value) return;
      SetValue(value);
    }
   }
  
   [XmlIgnore]
   public Activity Activity 
   {
    get 
    {
     if(ValueType == typeof(Activity))
     {
      return (Activity)SelectedValue;
     }
     throw new ChoiceTypeException($"Invalid Type: {nameof(Activity)}!");
    }
   }
  
   [XmlIgnore]
   public Container Container
   {
    get
    {
     if(ValueType == typeof(Container)
     {
      return (Container)SelectedValue;
     }
     throw new ChoiceTypeException($"Invalid Type: {nameof(Container)}!");
    }
   }
  }
  </code></pre>
  
  <p>ChildrenItem is my attempt at coding a xsd:choice in XML.</p>
  
  <p>Unfortunately, when I DeSerialize the XML from the WebService the Children collection is skipped.  </p>
  
  <p>1) How do I fix my objects so that they properly handle the XML?
  2) Is there a better way to handle xsd:choice elements than the way I am doing so here?</p>
  
  <p>Thanks and have a very Blessed Day!</p>