当前位置 : 主页 > 网页制作 > xml >

.net – 为什么XmlSerializer没有序列化我的数组?

来源:互联网 收集:自由互联 发布时间:2021-06-13
我是XmlSerializer的新手.我写了一个小类来保存数据库中的条目: [Serializable]public struct Entry{ public string artkey, lid, request, status, requestdate;} 很简单吧?序列化这些列表应该是小菜一碟. 我有
我是XmlSerializer的新手.我写了一个小类来保存数据库中的条目:

[Serializable]
public struct Entry
{
    public string artkey, lid, request, status, requestdate;
}

很简单吧?序列化这些列表应该是小菜一碟.

我有一个编译这些列表的函数.要序列化我的列表,我尝试以下代码:

XmlSerializer serializer = new XmlSerializer(typeof(Entry));
System.IO.MemoryStream ms = new System.IO.MemoryStream();
serializer.Serialize(ms, entries.ToArray());
ms.WriteTo(Response.OutputStream);

此代码打印以下异常:

<error>System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidCastException: Specified cast is not valid.
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterEntry.Write3_Entry(Object o)
   --- End of inner exception stack trace ---
   at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
   at System.Xml.Serialization.XmlSerializer.Serialize(Stream stream, Object o, XmlSerializerNamespaces namespaces)
   at System.Xml.Serialization.XmlSerializer.Serialize(Stream stream, Object o)
   at CCB_Requests.xmlResponse_selectFromCcb_Requests(HttpResponse response)
   at CCB_Requests.ProcessRequest(HttpContext context)</error>

看来我一定是犯了一个简单的错误.我怎样才能解决这个问题?

您正在序列化一个Entry数组,将XmlSerializer的初始化更改为:

// typeof(Entry) ==> typeof(Entry[])
XmlSerializer serializer = new XmlSerializer(typeof(Entry[]));
网友评论