There is a main class having 2 subClasses(each represent separate entity) and all classes needs to be serialized.. how should I proceed ? My requirement is when I serelize MainClass, I should get the xml for each sub class and main class as well. Thanks in advance... and if my approach is incorrect... correct that as well..
Ex given below...
class MainClass
{
SubClass1 objSubclass1 = null;
SubClass2 objSubclass2 = null;
public MainClass()
{
objSubclass1 = new SubClass1();
objSubclass2 = new SubClass2();
}
[XmlElement("SubClass1")]
public SubClass1 SubClass1 {get {r开发者_运维技巧eturn objSubclass1;} }
[XmlElement("SubClass2")]
public SubClass2 SubClass2 {get {return objSubclass2;} }
}
Class SubClass1
{
Some properties here...
}
Class SubClass2
{
Some properties here...
}
XML serialization requires the properties to be read/write. So you need to implement the get
and set
.
If you don't like that restriction, then you can implement IXmlSerializable (there's an example on the linked page), but it's probably more trouble than it's worth for such a simple requirement I would think.
For XML serialization to work with properties, you need to have both getters and setters for the properties.
Also, generally when the term subclass is used, it means a class that derives from a base class. This doesn't seem to be the case here so your example is a bit confusing.
If you actually do need to serialize subclasses, where the static type of a property is a base class, see the XmlIncludeAttribute.
精彩评论