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

时间:2015-05-11 11:11:58

标签: c# xml telerik expandoobject dynamicobject

我想使用ExpandoObjects列表作为Telerik报告的数据源,但似乎Telerik Reports目前不支持这一点。他们支持将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字符串?

1 个答案:

答案 0 :(得分:3)

您可以先将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())
    }
}