title: Using XmlAttributeOverrides on Nested Properties
body: <p>I am trying to use XmlAttributeOverrides to control which class properties appear in the xml after the class has been serialized.  It works on properties that are on the "root" class but not on nested properties.  Here is a simple example to illustrate what I'm trying to accomplish.</p>
  
  <p>My class hierarchy is as follows:</p>
  
  <pre><code>public class Main
  {
      public string Name { get; set; }
      public Location Address { get; set; }
  }
  
  public class Location
  {
      public string StreetAddress { get; set; }
      public Contact ContactInfo{ get; set; }
  }
  
  public class Contact
  {
      public string PhoneNumber { get; set; }
      public string EmailAddr { get; set; }
  }
  </code></pre>
  
  <p>When I serialize Main(), I get something like this:</p>
  
  <pre><code>&lt;Main&gt;
      &lt;Name&gt;&lt;/Name&gt;
      &lt;Address&gt;
          &lt;StreetAddress&gt;&lt;/StreetAddress&gt;
          &lt;ContactInfo&gt;
              &lt;PhoneNumber&gt;&lt;/PhoneNumber&gt;
              &lt;EmailAddr&gt;&lt;/EmailAddr&gt;
          &lt;/ContactInfo&gt;
      &lt;/Address&gt;
  &lt;/Main&gt;
  </code></pre>
  
  <p>What I am able to do is keep either Name or Address from appearing by using this:</p>
  
  <pre><code>XmlAttributeOverrides overrides = new XmlAttributeOverrides();
  XmlAttributes attribs = new XmlAttributes();
  attribs.XmlIgnore = true;
  attribs.XmlElements.Add(new XmlElementAttribute("Address"));
  overrides.Add(typeof(Main), "Address", attribs);
  xs = new XmlSerializer(typeof(Main), overrides);
  </code></pre>
  
  <p>What I need to also be able to do is keep Main.Address.ContactInfo from being serialized <strong>SOMETIMES</strong> (if it's empty).  I tried the following but they didn't work:</p>
  
  <pre><code>XmlAttributeOverrides overrides = new XmlAttributeOverrides();
  XmlAttributes attribs = new XmlAttributes();
  attribs.XmlIgnore = true;
  attribs.XmlElements.Add(new XmlElementAttribute("ContactInfo "));
  overrides.Add(typeof(Contact), "ContactInfo ", attribs);
  xs = new XmlSerializer(typeof(Contact), overrides);
  </code></pre>
  
  <p>and...</p>
  
  <pre><code>XmlAttributeOverrides overrides = new XmlAttributeOverrides();
  XmlAttributes attribs = new XmlAttributes();
  attribs.XmlIgnore = true;
  attribs.XmlElements.Add(new XmlElementAttribute("ContactInfo "));
  overrides.Add(typeof(Main.Address.ContactInfo), "ContactInfo ", attribs);
  xs = new XmlSerializer(typeof(Main.Address.ContactInfo), overrides);
  </code></pre>
  
  <p>I've actually tried a lot more, including using XPath statements to designate the attribute name to target but didn't want to fill this page up with failed attempts.  Is what I'm asking even possible by this method?</p>