XmlSerializing Base Classes

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • farseer

    XmlSerializing Base Classes

    let's say i have the following class that was generated using XSD.exe:

    [System.CodeDom. Compiler.Genera tedCodeAttribut e("xsd",
    "2.0.50727. 26")]
    [System.Serializ ableAttribute()]
    [System.Diagnost ics.DebuggerSte pThroughAttribu te()]
    [System.Componen tModel.Designer CategoryAttribu te("code")]
    [System.Xml.Seri alization.XmlTy peAttribute(Ano nymousType=true )]
    [System.Xml.Seri alization.XmlRo otAttribute(Nam espace="com.tes t.ns",
    IsNullable=fals e)]
    public class MyBaseClass {
    private string nameField;

    /// <remarks/>
    public string name{
    get {
    return this.nameField;
    }
    set {
    this.nameField= value;
    }
    }

    Now let's say in my app I extend this class so that i can add methods
    to it without having to touch the autogenerated class:

    public class MyClass1: MyBaseClass
    {
    public MyBaseClass getMyBaseClass {
    return (MyBaseClass) this;

    public void doSomething( ){...}
    }

    When i serialize this i'd like MyBaseClass to be serialized (i.e.the
    name "MyBaseClas s" should be the root element of the XML), so i added a
    method called getMyBaseClass which returns the base Class (as shown in
    the code above). i then do this to serialize:

    XmlSerializerNa mespaces xsNs = New XmlSerializerNa mespaces()
    xsNs.Add("n1", "com.test.n s")

    MyClass1 myClass = new MyClass1( )
    MyBaseClass myBase = myClass.getMyBa seClass( )
    XmlSerializer xs = new XmlSerializer( GetType( MyBaseClass ) )
    StringWriter sw = new StringWriter( )
    xs.Serialize( sw, myBase, xsNs )

    However, it appears when i attempt to do this, the serializer is
    complaining: "System.Invalid OperationExcept ion: There was an error
    generating the XML document. ---> System.InvalidO perationExcepti on: The
    type com.test.ns.MyC lass was not expected. Use the XmlInclude or
    SoapInclude attribute to specify types that are not known statically."

    WHAT AMI DOING WRONG? or how can i fix?

  • farseer

    #2
    Re: XmlSerializing Base Classes

    i have solved this by using encapsulation and delegation (rather than
    extending MyBaseClass, i create a private member of that type), but it
    would be VERY NICE to understand why extension is not able to work
    here.

    i seem to having a lot of problems with serialization and
    deserialization .

    Comment

    Working...