在DataContractSerializer上添加KnownTypeAttribute?

时间:2013-03-11 11:56:37

标签: c# .net serialization

我在WebForms中,我尝试将对象序列化为XML代码。好吧,使用:

using (FileStream writer = new FileStream("c:/temp/file.xml", FileMode.Create, FileAccess.Write))
{
    DataContractSerializer ser = new DataContractSerializer(videoContainer.GetType());
    ser.WriteObject(writer, videoContainer);
}

我收到此错误:输入数据合同名称为“YouTubeEntry:http://schemas.datacontract.org/2004/07/Google.GData.YouTube”的“Google.GData.YouTube.YouTubeEntry”不在预期范围内。将任何静态未知的类型添加到已知类型列表中 - 例如,使用KnownTypeAttribute属性或将它们添加到传递给DataContractSerializer的已知类型列表中。

所以我尝试了这个:

IEnumerable<string> lista = new List<string>();
lista.ToList().Add("YouTubeEntry:http://schemas.datacontract.org/2004/07/Google.GData.YouTube");

using (FileStream writer = new FileStream("c:/temp/file.xml", FileMode.Create, FileAccess.Write))
{
    DataContractSerializer ser = new DataContractSerializer(videoContainer.GetType(), lista);
    ser.WriteObject(writer, videoContainer);
}

传递KnownTypeAttribute列表,但似乎无法获取List? :O不确定我应该做什么...

2 个答案:

答案 0 :(得分:2)

您必须提供类型列表而不是字符串列表

var lista = new List<Type>();
lista.Add(typeof(Google.GData.YouTube.YouTubeEntry));

using (FileStream writer = new FileStream("c:/temp/file.xml", FileMode.Create, FileAccess.Write))
{
    DataContractSerializer ser = new DataContractSerializer(videoContainer.GetType(), lista);
    ser.WriteObject(writer, videoContainer);
}

答案 1 :(得分:1)

您应该将Type对象的集合传递给构造函数。不是字符串。

DataContractSerializer ser = new DataContractSerializer(videoContainer.GetType(), new List<Type> {typeof(YouTubeEntry)});