if i have some xml like this
<SiteSettings>
<sortOptions>
<add name="By Date" value="date" />
<add name="By Rating" value="rating" />
</sortOptions>
</SiteSettings>
I'd like to deserialise this into an object like this
[XmlRoot("SiteSettings")]
public class SerializableSiteSettings
{
public List<NameValuePair> SortOptions { get; set; }
}
public class NameValuePair
{
[XmlAttribute("name")]
public string Name { get; set; }
[XmlAttribute("value")]
public object Value { get; set; }
}
I tried adding this to the SortOptions but it did not work
[XmlArrayItem("actionButtons", typeof(List<NameValuePair>))]
public List<NameValuePair> ActionButtons { get; set; }
There are a few issues with your use of
XmlSerializer:XmlSerializerneeds to know the types to expect when (de)serializing. When you have a field likepublic object Value { get; set; }it has no idea how to deserialize the field or what to expect therein. You need to tell it that information -- but sinceValueis an attribute that suggests the field is something simple, like a string. So, I'm going to assume in this answer that a string is sufficient to hold this information.You need to tell
XmlSerializerthat your property namedSortOptionsis to be serialized with the namesortOptions, notSortOptions, using theXmlArrayattribute.You need to tell
XmlSerializerthataddis the name of each array element, using theXmlArrayItemattribute.Thus, the following works and reads
Valueinto a string:If
Valueis not a string and is really is some polymorphic type, you may need to implementIXmlSerializableforNameValuePair, along the lines of the following: .NET XmlSerializer: polymorphic mapping based on attribute value.