C# 将基类的集合动态序列化为XML
哦,海在那里 我想序列化和对象,如下所示:C# 将基类的集合动态序列化为XML,c#,generics,serialization,xml-serialization,C#,Generics,Serialization,Xml Serialization,哦,海在那里 我想序列化和对象,如下所示: public class Wrapper { [XmlArray("Entities"), XmlArrayItem("Entity")] public List<Base> Entities { get; set; } } 公共类包装器 { [XmlArray(“实体”)、XmlArrayItem(“实体”)] 公共列表实体{get;set;} } 我希望使应用程序尽可能灵活,因此在XmlArrayItem属性中设置手
public class Wrapper
{
[XmlArray("Entities"), XmlArrayItem("Entity")]
public List<Base> Entities { get; set; }
}
公共类包装器
{
[XmlArray(“实体”)、XmlArrayItem(“实体”)]
公共列表实体{get;set;}
}
我希望使应用程序尽可能灵活,因此在XmlArrayItem属性中设置手动派生的类类型不是一个选项,我如何动态地进行设置,即使序列化程序知道所有派生类
顺便说一句,我已经有了一个类来获取所有直接派生的类型,比如BaseDerived.DerivedClasses
和XmlSerializer cs=newxmlserializer(this.GetType(),BaseDerived.DerivedClasses)代码>不工作
有什么想法吗?找到了一个解决方案,在序列化过程中,你几乎可以直接插入项属性
所以首先收集属性,如
XmlAttributeOverrides xOver = new XmlAttributeOverrides();
XmlAttributes xAttrs = new XmlAttributes();
foreach (var cls in BaseDerived.DerivedClasses)
{
var attr = new XmlArrayItemAttribute(cls);
xAttrs.XmlArrayItems.Add(attr);
}
xOver.Add(this.GetType(), BaseDerived.GetMemberName((Wrapper x) => x.Entities), xAttrs);
顺便说一句:
public static string GetMemberName<T, TValue>(Expression<Func<T, TValue>> memberAccess)
{
return ((MemberExpression)memberAccess.Body).Member.Name;
}
XmlSerializer cs = new XmlSerializer(this.GetType(), xOver);