Vivian River
Vivian River

Reputation: 32380

Why doesn't XmlSerializer serialize my array?

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.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 that I must be making a simple mistake. How can I fix this?

Upvotes: 4

Views: 3591

Answers (3)

rhatwar007
rhatwar007

Reputation: 343

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());
    }

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062510

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

Upvotes: 1

manji
manji

Reputation: 47968

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

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

Upvotes: 5

Related Questions