'Serializable class: custom serializer for a collection property

I have an xml-serializable .net class which has a property of type List<string>. For backward-compatibility reasons I need to serialize/deserialize this property as a single comma-separated string. Like:

<MyProperty>ID1;ID2;ID3</MyProperty>

Is it possible to specify a custom serializer for only a particular property of a serializable class? Alternatively it is ok to implement ISerializable/IXmlSerializable for it, but in this case I would prefer to keep code to the minimum processing only that property and keeping the rest by default.

Any ideas?

Thanks!



Solution 1:[1]

XmlSerializer does not support this out of the box for attributes. And why would it, it kinda beats the purpose of XML. Xml has child props to handle this issue.

You could calculate your props as a fix, but this isn't clean and pretty slow if the list gets big.

[XmlAttribute(AttributeName = "attributeName")]
public string MyPropString{ get; set; }

public IList<string> MyProperty{
    get {
        return MyPropString.Split(';').Select(x => x.Trim()).ToList();
    }
    set {
       MyPropString = String.Join(";", value);
    }
}

This code could be wrong because i haven't tested it, but i hope you get the idea.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1