2012-11-28 22 views
0

我试图编写一个通用包装器来将一个通用对象列表序列化为一个xml文件,除了元素正在取代基类的名称而不是继承的类名有没有办法让它显示继承类的名称?从类名定义XmlElement

例如..

public class ObjectList 
{ 
[XmlElement("I want my inherited class here but it shows the base class object")] 
public List<Base> Items 
{ 
     get { return items; } 
} 
} 

public class Inherited : Base 
{ 
} 
+0

列表

+0

'名单 Items'并定义的类T的约束声明'公共类ObjectList 其中T:Base'。我不确定这会起作用,因为如果您在List中存储了多个干扰类型,那么XmlSerializer会根据您传递给序列化程序的类型来键入它们。可能会更好地定义一个接口。 – dash

回答

1

真可谓做到这一点的唯一方法就是设置替代

Type type = list.Items.First().GetType(); 
    string root = type.Name + "s"; 

    XmlElementAttribute myAttribute = new XmlElementAttribute(); 
    myAttribute.ElementName = type.Name; 

    XmlAttributes attribs = new XmlAttributes(); 
    attribs.XmlElements.Add(myAttribute); 

    XmlAttributeOverrides myOverride = new XmlAttributeOverrides(); 

    myOverride.Add(typeof(ObjectList), "Items", attribs); 

    XmlWriter xmlw = XmlWriter.Create(fileName); 
    XmlSerializer writer = new XmlSerializer(
       typeof(ObjectList), 
       myOverride, 
       new Type[] { type }, 
       null, 
       null);