1

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?

Community
  • 1
  • 1
patrickjlee
  • 180
  • 2
  • 12

1 Answers1

6

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())
    }
}
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • Thanks. This does indeed seem to work, although the XML produced from an ExpandoObject doesn't seem to be particularly useful (in general I think, whether from your code or anyone else's) because it serializes the underlying Dictionary used to hold the properties (field names) and values. For my purpose (of using this dynamic data as a data source for a Telerik Report) I found it was better to convert the List of ExpandoObjects to a DataTable (or perhaps bypass the expando objects and go straight to a DataTable) and use that as the data source. – patrickjlee May 12 '15 at 12:20