0

我正在尝试编写一个通用包装器来将通用对象列表序列化为一个 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
{
}
4

1 回答 1

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);
于 2012-11-29T11:27:21.993 回答