I want to use a List of ExpandoObjects as a datasource for a Telerik Report but it seems that Telerik Reports don't currently support this. They do support having XML as a data source, so I am trying to convert my List of ExpandoObjects to an XML string.
I have seen (at Can I serialize an ExpandoObject in .NET 4?) that an individual ExpandoObject can be serialized to an XML string via jsonFx via this (VB.net code, not c#):
dim XMLwriter As New JsonFx.Xml.XmlWriter
dim serializedExpando as string = XMLwriter.Write(obj)
or its equivalent c# code:
JsonFx.Xml.XmlWriter XMLwriter = new JsonFx.Xml.XmlWriter();
String serializedExpando = XMLwriter.Write(obj);
How can I serialize the whole list to an XML string?
You can serialize it by transforming the ExpandoObject
to an IDictionary<string, object>
first, and then using DataContractSerializer
for serialization:
void Main()
{
dynamic firstExpando = new ExpandoObject();
firstExpando.Name = "Name";
firstExpando.Age = 1;
dynamic secondExpando = new ExpandoObject();
secondExpando.Name = "SecondName";
secondExpando.Age = 2;
var expandoList = new List<ExpandoObject> {firstExpando, secondExpando};
var list = expandoList.Select(expando => (IDictionary<string, object>)expando)
.ToList();
var dataContractSerializer = new DataContractSerializer(list.GetType());
using (MemoryStream memoryStream = new MemoryStream())
{
dataContractSerializer.WriteObject(memoryStream, list);
string outputXml = Encoding.UTF8.GetString(memoryStream.ToArray())
}
}