title: XML Serialize dynamic object
body: <p>I need to construct a set of dynamically created XML nodes from objects on the following format:</p>
  
  <pre><code>&lt;Root&gt;
      &lt;Name&gt;My Name&lt;/Name&gt;
      &lt;DynamicValues&gt;
          &lt;DynamicValue1&gt;Value 1&lt;/DynamicValue1&gt;
          &lt;DynamicValue2&gt;Value 2&lt;/DynamicValue2&gt;
      &lt;/DynamicValues&gt;
  &lt;/Root&gt;
  </code></pre>
  
  <p>The name of the nodes within the <code>DynamicValues</code>-tag are not known in advance. My initial thought was that this should be possible using an <a href="http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.aspx" rel="noreferrer">Expando Object</a>, e.g:</p>
  
  <pre><code>[DataContract]
  public class Root
  {
      [DataMember]
      public string Name { get; set; }
  
      [DataMember]
      public dynamic DynamicValues { get; set; }
  }
  </code></pre>
  
  <p>by initializing it with the values:</p>
  
  <pre><code>var root = new Root
                      {
                          Name = "My Name",
                          DynamicValues = new ExpandoObject()
                      };
  
  root.DynamicValues.DynamicValue1 = "Value 1";
  root.DynamicValues.DynamicValue2 = "Value 2";
  </code></pre>
  
  <p>and then Xml-serialize it:</p>
  
  <pre><code>string xmlString;
  
  var serializer = new DataContractSerializer(root.GetType());
  using (var backing = new StringWriter())
  using (var writer = new XmlTextWriter(backing))
  {
      serializer.WriteObject(writer, root);
      xmlString = backing.ToString();
  }
  </code></pre>
  
  <p>However, when I run this, I get an SerializationException saying:</p>
  
  <blockquote>
    <p>"Type 'System.Dynamic.ExpandoObject' with data contract name
    'ArrayOfKeyValueOfstringanyType:<a href="http://schemas.microsoft.com/2003/10/Serialization/Arrays" rel="noreferrer">http://schemas.microsoft.com/2003/10/Serialization/Arrays</a>'
    is not expected. Consider using a DataContractResolver or add any
    types not known statically to the list of known types - for example,
    by using the KnownTypeAttribute attribute or by adding them to the
    list of known types passed to DataContractSerializer."</p>
  </blockquote>
  
  <p>Any ideas how I can achieve this? </p>