Fog Creek Software
Discussion Board




Welcome! and rules

Joel on Software

XmlSerialization breakage?

Does anyone know what the following error means?  It belongs to a very small C# program I wrote trying to get a handle on XmlSerialization.  Has anyone seen it?  Thanks.  (I can post the code if people need it, I just wasn't sure if it was needed right now.)

--- start ---

Unhandled Exception: System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidCastException: Specified cast is not valid.
  at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write3_ClassTest(Object o)
  --- End of inner exception stack trace ---
  at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle)
  at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o)
  at ClassTest.ClassTest.Main()

--- end ---

Andrew Burton
Friday, April 09, 2004

Does your object has a default constructor? Did you use any serialization attributes in the wrong places? You'll have to post your actual code, the error isn't very helpful.

Also, Dino Esposito ("Applied XML Programming for Microsoft .NET", pp. 483 ff) says a lot about XML serialization.

Chris Nahr
Saturday, April 10, 2004

Here's the code:

--- start code ---

using System;
using System.IO;
using System.Xml.Serialization;

namespace ClassTest
{

  public class ClassTest
  {

    public class Person {
      public string FName;
      public string LName;
      public string Species;
    }

    public static void Main ()
    {

      Person p = new Person();
      XmlSerializer xs = new XmlSerializer(typeof(ClassTest));

      p.FName = "Andy";
      p.LName = "Burton";
      p.Species = "Human";

      TextWriter sw = new StreamWriter("Text.xml");
      xs.Serialize(sw, p);
      sw.Close();

    }
  }
}

--- stop code ---

Andrew Burton
Sunday, April 11, 2004

You specified the wrong class name for the serializer! You want to serialize Person, not ClassTest.

Chris Nahr
Sunday, April 11, 2004

Oh my.

Thank you.

I'd like to say much more than "Thank you," but it's not possible with mere text.  Thank you.

Andrew Burton
Sunday, April 11, 2004

*  Recent Topics

*  Fog Creek Home