views:

93

answers:

1

I have a code like this:

[Serializable]
public class A {
    public int X { get; set; }
}
[Serializable]
public class B : A{        
}
[Serializable]
public class C {
    public A A { get; set; }
}
...
    public string Serialize<T>(T obj)
    {
        StringBuilder stringBuilder = new StringBuilder();
        TextWriter stringWriter = new StringWriter(stringBuilder);
        XmlWriter xmlWriter = new XmlTextWriter(stringWriter);
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        serializer.Serialize(xmlWriter, obj);
        xmlWriter.Close();
        stringWriter.Close();
        return stringBuilder.ToString();
    }

    private void Run() {
        C c = new C() {A = new B()};
        string str = Serialize(c);
    }

I have System.InvalidOperationException in execute of string str = SerializationManager.Serialize(c); with text "There was an error generating the XML document."

How I must write my code to serialize c without exception?

+6  A: 

You need to tell it about inheritance:

[XmlInclude(typeof(B)]
public class A {
    public int X { get; set; }
}
public class B : A{        
}

Note that you don't need [Serializable] for XmlSerializer.

Also - look at the inner exceptions:

try { ... }
catch (Exception ex) {
    while(ex != null) {
        Console.WriteLine(ex.Message);
        ex = ex.InnerException;
    }
}

To see:

"The type B was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."

Marc Gravell