Alexander Abakumov
Alexander Abakumov

Reputation: 14539

Serialize a List<KeyValuePair<string, object>>

Let's suppose we have an:

    public List<KeyValuePair<string, object>> Items { get; set; }

How can we serialize it as follows:

<!--<SomeEnclosingElement>-->
    <Key1>Value1.ToString()</Key1>
    <Key2>Value2.ToString()</Key2>
    ...
    <KeyN>ValueN.ToString()</KeyN>
<!--</SomeEnclosingElement>-->

using XmlSerializer, if possible, without custom implementation of IXmlSerializable?

Please note two things:

Upvotes: 1

Views: 1354

Answers (1)

dbc
dbc

Reputation: 116786

Given your requirement not to implement IXmlSerializable, you could add a public XElement[] surrogate property marked with [XmlAnyElement] to your type:

    [XmlIgnore]
    public List<KeyValuePair<string, object>> Items { get; set; }

    [XmlAnyElement]
    [Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DebuggerBrowsable(DebuggerBrowsableState.Never)]
    public XElement[] XmlItems
    {
        get
        {
            if (Items == null)
                return null;
            return Items.Select(p => new XElement(p.Key, (p.Value ?? string.Empty).ToString())).ToArray();
        }
        set
        {
            if (value == null)
                return;
            Items = Items ?? new List<KeyValuePair<string, object>>(value.Length);
            foreach (var e in value)
            {
                Items.Add(new KeyValuePair<string, object>(e.Name.LocalName, e.Value));
            }
        }
    }

The original property is marked with [XmlIgnore] while the surrogate property returns an array of XElement objects whose names are mapped from KeyValuePair.Key and whose values are mapped from KeyValuePair.Value.ToString().

Sample fiddle.

Upvotes: 1

Related Questions