加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:10:34 所属栏目:百科 来源:网络整理
导读:序列化包含派生对象列表的Dictionary时遇到问题.序列化输出包含 BaseAttributes xsi:type="Turbine" Id="1975fe1f-7aa8-4f1d-b768-93ad262800cd" 我希望BaseAttributes替换为Turbine,而xsi:type不存在. Turbine Id="1975fe1f-7aa8-4f1d-b768-93ad262800cd"
序列化包含派生对象列表的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))]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读