XmlSerializing Base Classes

F

farseer

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

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd",
"2.0.50727.26")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="com.test.ns",
IsNullable=false)]
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 "MyBaseClass" 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:

XmlSerializerNamespaces xsNs = New XmlSerializerNamespaces()
xsNs.Add("n1", "com.test.ns")

MyClass1 myClass = new MyClass1( )
MyBaseClass myBase = myClass.getMyBaseClass( )
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.InvalidOperationException: There was an error
generating the XML document. ---> System.InvalidOperationException: The
type com.test.ns.MyClass 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?
 
F

farseer

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top