不带xsi:类型的派生对象的序列化

本文关键字:派生 序列化 对象 类型 xsi 不带 | 更新日期: 2023-09-27 18:04:19

在序列化包含派生对象列表的Dictionary时遇到问题。序列化的输出包含

<BaseAttributes xsi:type="Turbine" Id="1975fe1f-7aa8-4f1d-b768-93ad262800cd">

我希望BaseAttributes替换为Turbine, xsi:类型不存在。

<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);

但是没有结果

不带xsi:类型的派生对象的序列化

今天又遇到了这个问题,很失望,所以没有答案。

如果它是一个字段或属性中的对象列表,则将此添加到顶部:

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

如果是单个对象,添加:

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

我已经解决了几乎相同的问题,但是与您发布的代码有更少或没有区别。

您是否尝试将属性作为方面放置在派生元素属性的顶部?我就是这样做的。此外,我还为所有的类添加了[Serializable]属性。