在c#中序列化嵌套类:指定要序列化的元素

时间:2015-12-04 07:12:34

标签: c# xml asp.net-mvc serialization asp.net-mvc-5

我有一个复杂的数据模型,我想序列化。每个类都有多个导航属性。如何设置需要遵循的导航路径。我添加了一个视图模型,仅指定了我需要序列化的类,但它会引发以下错误

  

反映类型

时出错

我也尝试通过直接调用父类来应用序列化。

预期产出

<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序列化功能

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);

视图模型

    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; }

但是在所有上述类的类定义中,定义了导航属性。我应该如何指定应该采用哪个属性进行序列化。我有上述类的许多属性和导航。如果我不希望所有属性都显示在XML文件中,应该怎么做。

例如Class OptionValue具有属性:

  • 名称
  • ID
  • CreatedBy
  • CreatedOn ...
  • ICollection的
  • ICollection的

但是在XML中我只想要名称ICollection。

我应该为每个模型类创建可序列化的ViewModel类吗?

0 个答案:

没有答案