title: XML serialization of objects with envelope in C#
body: <p>I need to serialize objects to XML in C#. The objects should be wrapped in an envelope. For that, I've created the following <code>Envelope</code> class:</p>
  
  <pre><code>[XmlInclude(typeof(Person))]
  public class Envelope
  {
      public string SomeValue { get; set; }
      public object WrappedObject { get; set; }
  }
  </code></pre>
  
  <p>I use the following code to serialize the class:</p>
  
  <pre><code>string fileName = ...;
  XmlSerializer serializer = new XmlSerializer(typeof(Envelope));
  TextWriter textWriter = new StreamWriter(fileName);
  try
  {
      serializer.Serialize(textWriter, &lt;instance of envelope&gt;);
  }
  finally
  {
      textWriter.Close();
  }
  </code></pre>
  
  <p>When I assign an object of type <code>Person</code> to <code>WrappedObject</code>, I get the following XML:</p>
  
  <pre><code>&lt;Envelope&gt;
      &lt;SomeValue&gt;...&lt;/SomeValue&gt;
      &lt;WrappedObject xsi:type="Person"&gt;
          ....
      &lt;/WrappedObject&gt;
  &lt;/Envelope&gt;
  </code></pre>
  
  <p>The problem is, I would like the tag for the wrapped object to be named after the actual class that I pass in. For example, if I assign an instance of <code>Person</code> to <code>WrappedObject</code>, I'd like the XML to look like the following:</p>
  
  <pre><code>&lt;Envelope&gt;
      &lt;SomeValue&gt;...&lt;/SomeValue&gt;
      &lt;Person&gt;
          ....
      &lt;/Person&gt;
  &lt;/Envelope&gt;
  </code></pre>
  
  <p>If I assign an instance of <code>Animal</code>, I'd like to get</p>
  
  <pre><code>&lt;Envelope&gt;
      &lt;SomeValue&gt;...&lt;/SomeValue&gt;
      &lt;Animal&gt;
          ....
      &lt;/Animal&gt;
  &lt;/Envelope&gt;
  </code></pre>
  
  <p>How would I achieve that?</p>
  
  <p><strong>EDIT</strong>  </p>
  
  <p>Actually I've simplified my example a little... The wrapped object is actually wrapped again:</p>
  
  <pre><code>public class Envelope
  {
      public string SomeValue { get; set; }
      public Wrapper Wrap { get; set; }
  }
  
  [XmlInclude(typeof(Person))]
  public class Wrapper
  {
      public object WrappedObject { get; set; }
  }
  </code></pre>
  
  <p>How would I handle this using the attributes override?</p>