如何将 List<ExpandoObject> 转换为 XML 字符串

How can I convert a List<ExpandoObject> to an XML string

我想使用 ExpandoObjects 列表作为 Telerik 报告的数据源,但 Telerik 报告目前似乎不支持此功能。他们确实支持将 XML 作为数据源,因此我正在尝试将我的 ExpandoObjects 列表转换为 XML 字符串。

我已经看到(在 Can I serialize an ExpandoObject in .NET 4?)可以通过 jsonFx 将一个单独的 ExpandoObject 序列化为一个 XML 字符串(VB.net 代码,而不是 c#):

dim XMLwriter As New JsonFx.Xml.XmlWriter
dim serializedExpando as string = XMLwriter.Write(obj)

或其等效的 c# 代码:

JsonFx.Xml.XmlWriter XMLwriter = new JsonFx.Xml.XmlWriter();
String serializedExpando  = XMLwriter.Write(obj);

如何将整个列表序列化为 XML 字符串?

您可以先将ExpandoObject转换为IDictionary<string, object>,然后使用DataContractSerializer进行序列化:

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())
    }
}