title: XmlAttributeOverrides attaching an attribute to an element
body: <p>I have the following code which is throwing an error...</p>
  
  <p>The error...</p>
  
  <blockquote>
    <p>For non-array types, you may use the following attributes: XmlAttribute, XmlText, XmlElement, or XmlAnyElement.</p>
  </blockquote>
  
  <p>The code (last line in Go method is throwing the exception)...</p>
  
  <pre><code>    public void Go(Type typeToSerialize, object itemToSerialize)
      {
          Dictionary&lt;string, bool&gt; processedList = new Dictionary&lt;string, bool&gt;();
          XmlAttributeOverrides overrides = new XmlAttributeOverrides();
  
          AttachXmlTransforms(overrides, itemToSerialize.GetType(), processedList);
  
          s = new XmlSerializer(typeToSerialize, overrides);
      }
  
      private static void AttachXmlTransforms(XmlAttributeOverrides overrides, Type root,
          Dictionary&lt;string, bool&gt; processedList)
      {
          foreach (PropertyInfo pi in root.GetProperties())
          {
              string keyName = pi.DeclaringType + "-" + pi.Name;
  
              if ((pi.PropertyType == typeof(DateTime) || pi.PropertyType == typeof(DateTime?))
                  &amp;&amp; !processedList.ContainsKey(keyName))
              {
                  XmlAttributes attributes = new XmlAttributes();
  
                  attributes.XmlElements.Add(new XmlElementAttribute(pi.Name));
                  //attributes.XmlAnyAttribute = new XmlAnyAttributeAttribute();
                  attributes.XmlAttribute = new XmlAttributeAttribute("dval");
  
                  //attributes.XmlIgnore = true;
  
                  processedList.Add(keyName, true);
  
  
                  overrides.Add(pi.DeclaringType, pi.Name, attributes);
              }
  
              if (pi.MemberType == MemberTypes.Property &amp;&amp; !pi.PropertyType.IsPrimitive
                  &amp;&amp; pi.PropertyType.IsPublic &amp;&amp; pi.PropertyType.IsClass
                  &amp;&amp; pi.PropertyType != typeof(DateTime))
              {
                  AttachXmlTransforms(overrides, pi.PropertyType, processedList);
              }
          }
      }
  </code></pre>
  
  <p>I'm attempting to add an attribute (dval) to only DateTime elements (this is an external requirement)...</p>
  
  <p>From this...</p>
  
  <pre><code>   &lt;CreatedDate&gt;01/01/2012&lt;/CreatedDate&gt;
  </code></pre>
  
  <p>To this...</p>
  
  <pre><code>   &lt;CreatedDate dval="01/01/2012"&gt;01/01/2012&lt;/CreatedDate&gt;
  </code></pre>
  
  <p>Is there a way to add an attribute to a normal non-array type element?</p>