title: How to decorate/define class members for an optional XML element to be used with XmlSerializer?
body: <p>I have the following XML structure.  The <code>theElement</code> element can contain <code>theOptionalList</code> element, or not:</p>
  
  <pre><code>&lt;theElement attrOne="valueOne" attrTwo="valueTwo"&gt;
      &lt;theOptionalList&gt;
          &lt;theListItem attrA="valueA" /&gt;
          &lt;theListItem attrA="anotherValue" /&gt;
          &lt;theListItem attrA="stillAnother" /&gt;
      &lt;/theOptionalList&gt;
  &lt;/theElement&gt;
  &lt;theElement attrOne="anotherOne" attrTwo="anotherTwo" /&gt;
  </code></pre>
  
  <p>What is a clean way to express the corresponding class structure?</p>
  
  <p>I'm pretty sure of the following:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Xml.Serialization;
  
  namespace MyNamespace
  {
      public class TheOptionalList
      {
          [XmlAttributeAttribute("attrOne")]
          public string AttrOne { get; set; }
  
          [XmlAttributeAttribute("attrTwo")]
          public string AttrTwo { get; set; }
  
          [XmlArrayItem("theListItem", typeof(TheListItem))]
          public TheListItem[] theListItems{ get; set; }
  
          public override string ToString()
          {
              StringBuilder outText = new StringBuilder();
  
              outText.Append("attrOne = " + AttrOne + " attrTwo = " + AttrTwo + "\r\n");
  
              foreach (TheListItem li in theListItems)
              {
                  outText.Append(li.ToString());
              }
  
              return outText.ToString();
          }
      }
  }
  </code></pre>
  
  <p>As well as:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Xml.Serialization;
  
  namespace MyNamespace
  {
      public class TheListItem
      {
          [XmlAttributeAttribute("attrA")]
          public string AttrA { get; set; }
  
          public override string ToString()
          {
              StringBuilder outText = new StringBuilder();
  
              outText.Append("  attrA = " + AttrA + "\r\n");                
              return outText.ToString();
          }
      }
  }
  </code></pre>
  
  <p>But what about for <code>theElement</code>?  Do I take the <code>theOptionalList</code> element as an array type to have it read what it finds in the file (either nothing, or one) and then check in code whether it's there or not?  Or is there another decorator that I can supply?  Or does it just work?</p>
  
  <p><strong>EDIT:</strong>  I ended up using information from <a href="https://stackoverflow.com/questions/3303165/using-xmlarrayitem-attribute-without-xmlarray-on-serializable-c-sharp-class/3303429#3303429">this answer</a>.</p>