XML : Serialize nested classes in c# : Specify what elements to be serialized

I have a complex data model which i want to serialize. Each class has multiple navigation properties. How do I set which path of navigation need to be followed. I added a View Model specifying only the classes I need to serialize but it throws the following error

There was an error reflecting type

I have also tried applying serialization by directly calling the parent class.

Expected Output

  <LsystemFamily>Family Name     <Lsystem>System Name1        <Option>Option1           <OptionValue> OptionValue1             <SetValue>                 Val 1.1                 Val 1.2             </SetValue>           </optionValue>           <OptionValue>OptionValue 2             <SetValue>                 Val 2.1                 Val 2.2             </SetValue>           </optionValue>         </Option>         <Option> Option 2           .....         </Option>      </Lsystem>      <Lsystem> Lsystem 2        ....      </Lsystem>  </Lsystemfamily>    

XML Serialize function

  var model = new export_test     {       Lsystem = new List<Lsystem>(),       Option = new List<Option>(),       OptionValue = new List<OptionValue>(),       SetValue = new List<SetValue>()     };  model.LsystemFamily = db.LsystemFamily.FirstOrDefault(x => x.LsystemFamilyID != 0);  model.Lsystem = db.Lsystem.Where(x => x.LsystemFamilyID == model.LsystemFamily.LsystemFamilyID).ToList();  foreach (var item in model.Lsystem)      model.Option = db.Option.Where(x => x.LsystemID == item.LsystemID).ToList();  foreach (var item in model.Option)      model.OptionValue = db.OptionValue.Where(x => x.OptionID == item.OptionID).ToList();  foreach (var item in model.OptionValue)      model.SetValue = db.SetValue.Where(x => x.OptionValueID == item.OptionValueID).ToList();    var serializer = new XmlSerializer(typeof(export_test));  StreamWriter writer = new StreamWriter(@"C:\Visual Studio 2013\Projects\TEDALS-Ver01.4\xml\newxml.xml");  serializer.Serialize(writer.BaseStream, model);    

ViewModel

      public virtual LsystemFamily LsystemFamily { get; set; }      public virtual List<Lsystem> Lsystem {get;set;}      public virtual List<Option> Option { get; set; }      public virtual List<OptionValue> OptionValue { get; set; }      public virtual List<SetValue> SetValue { get; set; }    

But in the class definition of all the above classes there are navigation properties defined. How should I specify which property should be taken for serialization. I have many properties and Navigation for the above classes. What should be done if I do not want all the properties to be displayed in the XML file.

For instance Class OptionValue has properties :

  • Name
  • ID
  • CreatedBy
  • CreatedOn...
  • ICollection
  • ICollection

But in the XML i only want the name, ICollection.

Should I create serializable ViewModel classes for each model classes?

No comments:

Post a Comment