title: Linq To Xml Saving a List Of Nested Objects
body: <p>I currently load an XML file into a list objects using code like this </p>
  
  <pre><code>    XDocument xmlDoc = XDocument.Load(path);
      List&lt;ImportDefinition&gt; importDefinitions = xmlDoc.Descendants("Root").Select(xElem =&gt; (ImportDefinition)xElem).ToList();
      return importDefinitions;
  </code></pre>
  
  <p>This list of objects contains nested objects and each one has an operator for parsing the XML into the correct form like this</p>
  
  <pre><code>public static explicit operator Rules(XElement xElem)
  {
      try
      {
          return new Rules()
          {
              FileNameRegEx = (string)xElem.Element("FileNameRegEx"),
              FileExtension = (string)xElem.Element("FileExtension")
          };
      }
      catch (Exception ex)
      {
          return null;
      }
  </code></pre>
  
  <p>This works fine for loading the XML. I now want to save this list of objects back to XML after some edits have been made.</p>
  
  <p>I was hoping something like this would work</p>
  
  <pre><code>  XElement xml = new XElement("Root",
                               from p in ObjectList
                               select new XElement("File",RootObject
                                   ));
      }
      xml.Save("C:\\temp\\newimport.xml");
  </code></pre>
  
  <p>However this just seems to output this</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;Root&gt;
    &lt;File&gt;MyNamespace.RootObject&lt;/File&gt;
    &lt;File&gt;MyNamespace.RootObject&lt;/File&gt;
  &lt;/Root&gt;
  </code></pre>
  
  <p>It looks like its not using the custom operators it uses when loading the files to work out the format to save in. Whats the best way to save this data back to XML to the same format it was in when I read it?</p>