Why doesn't XmlSerializer serialize my array?

I am new to XmlSerializer. I wrote a small class for storing records from a database:

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

Simple enough, right? It must be a piece of cake to serialize a list of them.

I have a function that compiles their list. To serialize my list, I try the following code:

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

This code prints the following exception:

 <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> 

It seems I should make a simple mistake. How can i fix this?

+4
source share
3 answers

you serialize an array Entry , change the initialization of the XmlSerializer to:

 // typeof(Entry) ==> typeof(Entry[]) XmlSerializer serializer = new XmlSerializer(typeof(Entry[])); 
+5
source

Writing this as a wiki since it does not answer the question, but show how this type should be written:

 public class Entry {  [XmlElement("artKey")] public string ArtKey {get;set;} // etc } 

for reasons, see comments added to qestion

+1
source

Do not use typeof (), once your record is Null or in Faulted state, then it shows an InvalidCastException, therefore, in addition to the GetType () method, you will get the same result as 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()); } 
0
source

Source: https://habr.com/ru/post/1345903/


All Articles