c# – 没有xsi:type的派生对象的序列化

序列化包含派生对象列表的Dictionary时遇到问题.序列化输出包含
<BaseAttributes xsi:type="turbine" Id="1975fe1f-7aa8-4f1d-b768-93ad262800cd">

我希望BaseAttributes替换为turbine,而xsi:type不存在.

<turbine Id="1975fe1f-7aa8-4f1d-b768-93ad262800cd">

我的整体代码如下所示.我有一个类BaseAttributes,我从中派生出一些类,例如turbine类.这些类存储在带有BaseAttributes列表的字典中.字典是实现的可序列化字典.以下是一般的代码.

[XmlInclude(typeof(turbine)),XmlInclude(typeof(Station)),XmlInclude(typeof(Substation))]
public class BaseAttributes {

  [XmlAttribute("Id")]
  public Guid Id;
}



public class turbine : BaseAttributes {
  private Element windSpeed;
  public Element WindSpeed {
    get { return windSpeed; }
    set { windSpeed = value; }
  }

  public turbine(float windSpeed){
    this.windSpeed= new Element(windSpeed.ToString(),"ms");
  }
  //used for xmlserilization
  private turbine(){}
}



public class CollectionOfBaseAttributes {
  public SerilizableunitsDictionary<DateTime,List<BaseAttributes>> units;
}

[XmlRoot("dictionary")]
public class SerilizableunitsDictionary<TKey,TValue>
: Dictionary<TKey,TValue>,IXmlSerializable {

  public System.Xml.Schema.XmlSchema GetSchema() {
    return null;
  }

  public void WriteXml(System.Xml.XmlWriter writer) {

    XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue),new XmlRootAttribute("Units"));

    foreach (TKey key in this.Keys) {
    writer.WriteStartElement("TimeStamp");              
    writer.WriteAttributeString("Value",key.ToString());

    TValue value = this[key];
    foreach (TValue value1 in Values) {             
      valueSerializer.Serialize(writer,value1);    
    }

    writer.WriteEndElement();
  }
}

我没有使用DataContractor进行序列化,因为我不会反序列化XML.我“只是”想要创建带有属性的XML文件.

我曾尝试使用XmlElementOverrides,但可能还有一些我在使用中无法理解的东西.目前我试图像这样使用它:

XmlAttributes attrs = new XmlAttributes();
XmlElementAttribute attr = new XmlElementAttribute();
attr.ElementName = "turbine";
attr.Type = typeof(turbine);
attrs.XmlElements.Add(attr);
XmlAttributeOverrides attrOverrides = new XmlAttributeOverrides();
attrOverrides.Add(typeof(CollectionOfBaseAttributes ),"BaseAttributes",attrs);

XmlSerializer xmlSerializer = new XmlSerializer(typeof(CollectionOfBaseAttributes ),attrOverrides);

但没有结果.

解决方法

今天再次进入它并且失望所以没有答案.

如果它是字段或属性中的对象列表,请将其添加到顶部:

[XmlArrayItem(Type = typeof(turbine))]
[XmlArrayItem(Type = typeof(Station))]

如果是单个对象添加

[XmlElement(Type = typeof(turbine))]
 [XmlElement(Type = typeof(Station))]

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...