从类名定义XmlElement

时间:2012-11-28 11:48:01

标签: c# xml serialization

我正在尝试编写一个通用包装器来将通用对象列表序列化为xml文件,除了元素采用基类的名称而不是继承的类名之外,一切正常。有没有如何让它显示继承类的名称?

例如......

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

1 个答案:

答案 0 :(得分: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);