简体   繁体   中英

How to serialize XML without writing the type as a tag

I am trying to write out an XML file, by serializing my class. The class includes a dictionary<string,object> called OptionList, and I have used some code I found here on Stack Overflow to create a serializable dictionary: https://stackoverflow.com/a/1728996/3364648

However, it's not quite giving me what I want. After tweaking the code slightly, I'm getting closer. My WriteXml now looks like this:

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

and outputs this:

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

What I want as output is this:

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

Any ideas on how to replace <string> with <key> and <anytype> with <value> ?

How about this:

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

No need serializer. Do work manual.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM