我是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>
似乎我必须犯一个简单的错误。我该如何解决这个问题?
答案 0 :(得分:5)
您正在序列化Entry
的数组,将XmlSerializer
的初始化更改为:
// typeof(Entry) ==> typeof(Entry[])
XmlSerializer serializer = new XmlSerializer(typeof(Entry[]));
答案 1 :(得分:1)
将其写为维基,因为它没有回答这个问题,但是要说明应该如何写这个类型:
public class Entry
{
[XmlElement("artKey")]
public string ArtKey {get;set;}
// etc
}
由于原因,请参阅我添加到qestion的评论
答案 2 :(得分:0)
不要使用typeof()有时候你的Entry是Null或者是Faulted State然后它显示InvalidCastException,所以除了使用GetType()方法之外,它将提供与typeof()相同的输出。
Entry e = new Entry();
e.artkey = "as";
e.lid = "lid";
e.request = "request";
e.requestdate = "req uesteddate";
e.GetType();
try(e!=null)
{
XmlSerializer serializer = new XmlSerializer(e.GetType());
}