Search code examples
c#.netxml-serializationdatacontractserializer

How to format serialization of IDictionary with DataContractSerializer?


I am using the following code to Serialize / Deserialize from object to XML

using System.Runtime.Serialization;
public static string Serialize<T>(this T obj)
        {
            var serializer = new DataContractSerializer(obj.GetType());
            using (var writer = new StringWriter())
            using (var stm = new XmlTextWriter(writer))
            {
                serializer.WriteObject(stm, obj);
                return writer.ToString();
            }
        }

        public static T Deserialize<T>(this string serialized)
        {
            var serializer = new DataContractSerializer(typeof(T));
            using (var reader = new StringReader(serialized))
            using (var stm = new XmlTextReader(reader))
            {
                return (T)serializer.ReadObject(stm);
            }
        }

To make this code work with IDictionary, i have the following custom Dictionary class:

[CollectionDataContract(Name = "Kenan", ItemName="Items", KeyName="Row", Namespace="spell", ValueName="Values")]
public class CustomRowList : Dictionary<RowXML, List<ColumnXML>>
{

}

The problem is, that when the code outputs my

Dictionary<RowXML, List<ColumnXML>>

it looks like this:

enter image description here

I do not need the <Items> and <Values> nodes. Instead, i would like it for output it as:

<RowList>
<Row>
<Title></Title>
<Help_Text></Help_Text>
<ClassName></ClassName>
<ColumnList>
<Column>
<ClassName></ClassName>
<Help_Text></Help_Text>
<Title></Title>
</Column>
<Column>
...

How can i make DataContractSerializer format my Dictionary in this way? I tried setting the

ItemName

And

ValueName

on

[CollectionDataContract]

Properties to blank, but this didnt work.


Solution

  • Looks like, you want to customize the xml output of your collection class. Only way to achieve this expected output is to implement the IXmlSerializable interface as below.

    [CollectionDataContract(Name = "Kenan", ItemName="Items", KeyName="Row", Namespace="spell", ValueName="Values")]
    public class CustomRowList : Dictionary<RowXML, List<ColumnXML>>, IXmlSerializable 
    {
    
    }
    

    Please look here for more information

    Proper way to implement IXmlSerializable?