title: streaming XML serialization in .net
body: <p>I'm trying to serialize a very large <code>IEnumerable&lt;MyObject&gt;</code> using an <code>XmlSerializer</code> without keeping all the objects in memory.</p>
  
  <p>The <code>IEnumerable&lt;MyObject&gt;</code> is actually lazy..</p>
  
  <p>I'm looking for a streaming solution that will:</p>
  
  <ol>
  <li>Take an object from the <code>IEnumerable&lt;MyObject&gt;</code>
  Serialize it to the underlying stream using the standard serialization (<em>I don't want to handcraft the XML here!</em>)</li>
  <li>Discard the in memory data and move to the next</li>
  </ol>
  
  <p>I'm trying with this code:</p>
  
  <pre><code>using (var writer = new StreamWriter(filePath))
  {
   var xmlSerializer = new XmlSerializer(typeof(MyObject));
    foreach (var myObject in myObjectsIEnumerable)
    {
     xmlSerializer.Serialize(writer, myObject);
    }
  }
  </code></pre>
  
  <p>but I'm getting multiple XML headers and I cannot specify a root tag <code>&lt;MyObjects&gt;</code> so my XML is invalid.</p>
  
  <p>Any idea?</p>
  
  <p>Thanks</p>