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

时间:2015-11-24 16:26:10

标签: c# xml serialization

我试图通过序列化我的类来写出一个XML文件。该类包含一个名为OptionList的dictionary<string,object>,我使用了一些我在Stack Overflow上找到的代码来创建一个可序列化的字典:the documentation on the DO_NOTHING option

然而,它并没有完全给我我想要的东西。稍微调整一下代码后,我就越来越近了。我的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>

有关如何将<string><key><anytype>替换为<value>的任何想法?

1 个答案:

答案 0 :(得分:1)

这个怎么样:

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

不需要序列化程序。做工作手册。