开发者

Why doesn't XmlSerializer serialize my array?

开发者 https://www.devze.com 2023-02-21 00:29 出处:网络
I\'m new to the XmlSerializer.I\'ve written a small class to hold entries from a database: [Serializable]

I'm new to the XmlSerializer. I've written a small class to hold entries from a database:

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

Simple enough, right? It should be a piece of cake to serialize a list of these.

I have a function that compiles a list of these. 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.Generate开发者_运维问答dAssembly.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 that I must be making a simple mistake. How can I fix this?


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

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


Writing this as wiki, as it doesn't 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 the comments I added to the qestion


Dont use typeof() sometime is your Entry is Null or in Faulted State then it shows InvalidCastException so apart from that use GetType() method which will gives you same output as by 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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号