public void Serialize(object[] messages, Stream messageStream) { if (messages.Length > MaxNumberOfAllowedItemsInCollection) { throw new UnboundedResultSetException("A message batch is limited to 256 messages"); } var namespaces = GetNamespaces(messages); var messagesElement = new XElement(namespaces["esb"] + "messages"); var xml = new XDocument(messagesElement); foreach (var m in messages) { if (m == null) { continue; } try { WriteObject(reflection.GetNameForXml(m.GetType()), m, messagesElement, namespaces); } catch (Exception e) { throw new SerializationException("Could not serialize " + m.GetType() + ".", e); } } messagesElement.Add( namespaces.Select(x => new XAttribute(XNamespace.Xmlns + x.Key, x.Value)) ); var streamWriter = new StreamWriter(messageStream); var writer = XmlWriter.Create(streamWriter, new XmlWriterSettings { Indent = true, Encoding = Encoding.UTF8 }); if (writer == null) { throw new InvalidOperationException("Could not create xml writer from stream"); } xml.WriteTo(writer); writer.Flush(); streamWriter.Flush(); }