c# - xml serializing a list of base class -


consider below class structure

[xmlinclude(typeof(derivedclass))] public class baseclass {     public string mem1;     public string mem2; }  public class derivedclass : list<baseclass> {     public string mem3;     public string mem4; }  class program {     static void main(string[] args)     {         derivedclass obj = new derivedclass();         obj.mem3 = "test3";         obj.mem4 = "test4";         baseclass base11 = new baseclass();         base11.mem1 = "test1";         base11.mem2 = "test2";         obj.add(base11);         xelement            .parse(xmlserializerutil.getxmlfromobject(obj))            .save(@"c:\new_settings1.xml");     } } 

the code getxmlfromobject given below

public static string getxmlfromobject(object instance) {         string retval = string.empty;         if (instance != null)         {             xmlserializer xmlserializer = new xmlserializer(instance.gettype());             using (memorystream memorystream = new memorystream())             {                 xmlserializer.serialize(memorystream, instance);                 memorystream.position = 0;                 retval = new streamreader(memorystream).readtoend();             }         }         return retval;     } 

even after adding xmlinclude attribute, in generated xml file, derived class members not present.

<?xml version="1.0" encoding="utf-8"?> <arrayofbaseclass xmlns:xsd="http://www.w3.org/2001/xmlschema"   xmlns:xsi="http://www.w3.org/2001/xmlschema-instance">     <baseclass>         <mem1>test1</mem1>         <mem2>test2</mem2>     </baseclass> </arrayofbaseclass> 

please let me know, missing include derived class members in generated xml file.

here's problem:

derivedclass : list<baseclass> 

for xmlserializer, item either list exclusive-or entity. if looks list, only list-items serialized; members of "list" are not serialized. basically, don't that. instead of deriving list, encapsulate list:

also, note [xmlinclude(...)] expect derivedclass : baseclass. so, like:

public class sometype // note not inherit {     private readonly list<someothertype> items = new list<someothertype>();     public list<someothertype> items { { return items; } }     [xmlelement("mem3")] public string mem3 {get;set;}     [xmlelement("mem4")] public string mem4 {get;set;} }  public class someothertype {     [xmlelement("mem1")] public string mem1 {get;set;}     [xmlelement("mem2")] public string mem2 {get;set;} } 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -