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

前端之家收集整理的这篇文章主要介绍了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))]
原文链接:https://www.f2er.com/csharp/100994.html

猜你在找的C#相关文章