c# - XML deserialization of derived classes -
How can I create a deserialization method that can take any object of class or object derived classes?
public class conference {public string appname; } Public class CustomConfig1: Configure {public string CustomConfig1Param1; Public string CustomConfig1Param2; } Public class CustomConfig2: Configure {public string CustomConfig2Param1; Public string CustomConfig2Param2; } I have to do something like the serialization method which defines the type of input object:
public string string (object obj) {XmlSerializer serializer = New XmlSerializer (obj.GetType ()); StringRitter Stylized = New Stringwriter (); Serializer.Serialize (serialized, obj); Return Serial ..ToString (); } But when I read an XML from DB, then I can not define the type of object, so I can not do it with XmlSerializer Em> Config can be any of the objects or derivative classes
Please help how can I define the type of input object?
[XmlInclude (CustomConfig1)] [XmlInclude (typeof (CustomConfig2)]] Public class configuration {public string appname; } Then just specify typeof () serialize / decrylize; The library will give you an example of the appropriate type depending on the data.
Edit: Full example, with no preference for hard-code subtype:
using system; Using System.IO; Using System.Xml.Serialization; Public class configuration {public string appname; } Public class CustomConfig1: Configure {public string CustomConfig1Param1; Public string CustomConfig1Param2; } Public class CustomConfig2: Configure {public string CustomConfig2Param1; Public string CustomConfig2Param2; } Fixed class program {static zero main () {var original = new custom config 1 {appname = "foo", CustomConfig1Param1 = "x", CustomConfig1Param2 = "y"}; Var xml = Serial tax (original); Var clone = desialize conifef (xmg); Console.WriteLine (clone.appname); Var Type = (CustomConfig1) Clone; Console.WriteLine (typed.CustomConfig1Param1); Console.WriteLine (typed.CustomConfig1Param2); } {GetConfigSerializer () using the public static string serialize (configured obje) {(serialized = new string water ()). Serialized (serialized, obez); Return Serial ..ToString (); }} {Return (gate) gateconfig certifiers () using public static config deserialos config (string xml) {(var reader = new string reader (XML) Differentiate (reader); }} Fixed Type [] GetKnownTypes () {// TODO: Fixes types correctly New [] Returns {Typef (Custom Conflict 1), Typef (Custom Conflict 2)}; } Private Static XmlSerializer configSerializer; Public Stable XmlSerializer GetConfigSerializer () {Return ConfigSerializer ?? (ConfigSerializer = New XmlSerializer (type (config), GetKnownTypes ())); }}
Comments
Post a Comment