title: Controlling XmlSerializer for Class depending on if it is an Attribute of XMLElement
body: <p>I have a class that is included in other classes as a variable, and needs to be serialized along with the other classes as XML. In some classes it will be included as an attribute, and the rest it will be an element. Is there an easy way to handle this using <code>XMLSerializer</code>. </p>
  
  <p>For the sake of making this clearer here is an example. I have Class <code>B</code>:</p>
  
  <pre><code>public class B {
  
      public string name { get; set; }
  
      public string description { get; set; }
  
      public B() { }
  
      public B(string name, string description) {
          this.name = name;
          this.description = description;
      }
  }
  </code></pre>
  
  <p>Then Class <code>A</code>:</p>
  
  <pre><code>public class A {
      [XmlAttribute("aName")]
      public string name { get; set; }
  
      [XmlAttribute("bName")]
      public B b { get; set; }
  
      public A() { }
  
      public A (string name, B b){
          this.name = name;
          this.b = b;
      }                
  }
  </code></pre>
  
  <p>Then to serialize it I do:</p>
  
  <pre><code>XmlSerializer serializer = new XmlSerializer(typeof(A));
  TextWriter textWriter = new StreamWriter(@"C:\Test.xml");
  serializer.Serialize(textWriter, new A("A Name", new B("B Name", "B Description")));
  textWriter.Close();
  </code></pre>
  
  <p>I know I could change Class <code>A</code> to:</p>
  
  <pre><code>public class A {
      [XmlAttribute("aName")]
      public string name { get; set; }
  
      [XmlIgnore]
      public B b { get; set; }
  
      [XmlAttribute("bName")]
      public string bXml {get{return b==null ? null : b.name;} set{this.b = new B(value, null);}}
  
      public A() { }
  
      public A (string name, B b){
          this.name = name;
          this.b = b;
      }                
  }
  </code></pre>
  
  <p>But since this happens in multiple locations, it would be nice to not have to add the <code>bXML</code> in every class that wants to use it as an attribute instead of as an element. I was hoping there was a way to set a converter when I want to this, or even add code to Class <code>B</code> for <code>asAttribute</code> and <code>asElement</code>.</p>