如何在不将类型写入标记的情况下序列化XML

本文关键字:情况下 XML 序列化 类型 | 更新日期: 2023-09-27 18:24:13

我正试图通过序列化我的类来编写一个XML文件。该类包括一个名为OptionList的dictionary<string,object>,我使用了在Stack Overflow上找到的一些代码来创建一个可序列化字典:https://stackoverflow.com/a/1728996/3364648

然而,它并没有给我想要的。在稍微调整了代码之后,我离它越来越近了。我的WriteXml现在看起来是这样的:

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        XmlSerializer keySerializer = new XmlSerializer(typeof(TKey));
        XmlSerializer valueSerializer = new XmlSerializer(typeof(TValue));
        foreach (TKey key in this.Keys)
        {
            writer.WriteStartElement("Option");
            keySerializer.Serialize(writer, key);
            writer.WriteStartElement("value");
            TValue value = this[key];
            valueSerializer.Serialize(writer, value);
            writer.WriteEndElement();
            writer.WriteEndElement();
        }
    }

并输出:

  <OptionList>
    <Option>
      <string>UNCOMMITTED</string>
      <value>
        <anyType xsi:type="xsd:boolean">true</anyType>
      </value>
    </Option>
    <Option>
      <string>DEADLOCK</string>
      <value>
        <anyType xsi:type="xsd:boolean">true</anyType>
      </value>
    </Option>
  </OptionList>

我想要的输出是:

  <OptionList>
    <Option>
      <key>UNCOMMITTED</key>
      <value xsi:type="xsd:boolean">true</value>
    </Option>
    <Option>
      <key>DEADLOCK</key>
      <value xsi:type="xsd:boolean">true</value>
    </Option>
  </OptionList>

如何用<key>代替<string>,用<value>代替<anytype>

如何在不将类型写入标记的情况下序列化XML

这个怎么样:

public void WriteXml(XmlWriter writer)
{
    foreach (TKey key in this.Keys)
    {
        writer.WriteStartElement("Option");
        writer.WriteElementString("key", key.ToString());
        TValue value = this[key];
        writer.WriteElementString("value", value.ToString());
        writer.WriteEndElement();
    }
}

不需要序列化程序。操作手册。