Cast errors with IXmlSerializable

Posted by Nathan on Stack Overflow See other posts from Stack Overflow or by Nathan
Published on 2010-05-05T03:18:52Z Indexed on 2010/05/05 3:28 UTC
Read the original article Hit count: 304

Filed under:
|
|

I am trying to use the IXmlSerializable interface to deserialize an Object (I am using it because I need specific control over what gets deserialized and what does not. See my previous question for more information). However, I'm stumped as to the error message I get. Below is the error message I get (I have changed some names for clarity):

An unhandled exception of type 'System.InvalidCastException' occurred in App.exe

Additional information: Unable to cast object of type 'System.Xml.XmlNode[]' to type 'MyObject'.

MyObject has all the correct methods defined for the interface, and regardless of what I put in the method body for ReadXml() I still get this error. It doesn't matter if it has my implementation code or if it's just blank.

I did some googling and found an error that looks similar to this involving polymorphic objects that implement IXmlSerializable. However, my class does not inherit from any others (besides Object). I suspected this may be an issue because I never reference XmlNode any other time in my code.

Microsoft describes a solution to the polymorphism error: https://connect.microsoft.com/VisualStudio/feedback/details/422577/incorrect-deserialization-of-polymorphic-type-that-implements-ixmlserializable?wa=wsignin1.0#details

The code the error occurs at is as follows. The object to be read back in is an ArrayList of "MyObjects"

        IO::FileStream ^fs = gcnew IO::FileStream(filename, IO::FileMode::Open);
        array<System::Type^>^ extraTypes = gcnew array<System::Type^>(1);
        extraTypes[0] = MyObject::typeid;
        XmlSerializer ^xmlser = gcnew XmlSerializer(ArrayList::typeid, extraTypes);

        System::Object ^obj;
        obj = xmlser->Deserialize(fs);
        fs->Close();

        ArrayList ^al = safe_cast<ArrayList^>(obj);
        MyObject ^objs;
        for each(objs in al) //Error occurs here
        {
            //do some processing
        }

Thanks for reading and for any help.

© Stack Overflow or respective owner

Related posts about c#

Related posts about deserialize