streaming XML serialization in .net

Posted by Luca Martinetti on Stack Overflow See other posts from Stack Overflow or by Luca Martinetti
Published on 2009-04-06T13:51:41Z Indexed on 2010/03/27 3:03 UTC
Read the original article Hit count: 327

Filed under:
|
|
|
|

Hello,

I'm trying to serialize a very large IEnumerable<MyObject> using an XmlSerializer without keeping all the objects in memory.

The IEnumerable<MyObject> is actually lazy..

  1. I'm looking for a streaming solution that will:

  2. Take an object from the IEnumerable<MyObject> Serialize it to the underlying stream using the standard serialization (I don't want to handcraft the XML here!)

  3. Discard the in memory data and move to the next

I'm trying with this code:

using (var writer = new StreamWriter(filePath))
{
 var xmlSerializer = new XmlSerializer(typeof(MyObject));
  foreach (var myObject in myObjectsIEnumerable)
  {
   xmlSerializer.Serialize(writer, myObject);
  }
}

but I'm getting multiple XML headers and I cannot specify a root tag <MyObjects> so my XML is invalid.

Any idea?

Thanks

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET