Reputation: 35679
I've got an interface that two classes implement at the moment. The data for these classes is read in from an xml file.
e.g.
[Serializable]
public interface IMyInterface { }
[Serializable]
public class MyClass1 : IMyInterface { }
[Serializable]
public class MyClass2 : IMyInterface { }
I want to infer the type from the Xml, is there a way of doing that?
So for example my xml looks like this:
<meta type="MyClass1">
<!--- Some meta data -->
</meta>
I want to be able to directly serialize from xml into objects. Currently I'm manually processing the xml.
Edit: To clarify, I know how to serialize out but I can't serialize back in without knowing which type it is first. Should I read the type attribute and then serialize based on that?
Upvotes: 0
Views: 199
Reputation: 1493
If I understand your query correctly...
Have a property in your interface, say
[Serializable]
public interface IMyInterface
{
YourClassDifferentiatorEnum ObjectDifferentiator { get; set; }
}
And let each class set this value with distinct enum value. Serialize these concrete class into XML.
When you want to deserialize (XML back to concrete object), then deserialise it to IMyInterface
, check for the object differentiator, and cast accordingly.
Upvotes: 1
Reputation: 161773
The XML Serializer is not meant for situations like this. It's meant for serializing objects that can be mapped in to XML described by an XML Schema.
On the other hand, runtime serialization includes a SOAP Formatter that can serialize objects, including details of their .NET types. So can the NetDataContractSerializer in WCF.
Upvotes: 1
Reputation: 51214
If you are using XmlSerializer, you can add the XmlIncludeAttribute to specify the derived classes that can be deserialized. But the thing is that you have to add it to the base class:
[XmlInclude(typeof(DerivedClass))]
public abstract class BaseClass
{
public abstract bool Property { get; set; }
}
public class DerivedClass : BaseClass
{
public override bool Property { get; set; }
}
Other way would be to implement IXmlSerializable for the member that can be derived, and then have a Factory for derived classes based on an attribute (or is that what you are doing right now?)
Upvotes: 1
Reputation: 18013
I don't know if this can help, but here it goes...
What if you put a public property on the classes that returns the typename
[XmlAttribute]
public string Type {
get { return GetType().Name; }
}
Upvotes: -1