Search code examples
c#collectionsxml-serializationwrappercamelcasing

XMLSerializer keeps capitalizing items in collection


I need to export a collection of items in camel casing, for this I use a wrapper.

The class itself:

[XmlRoot("example")]
public class Example
{
    [XmlElement("exampleText")]
    public string ExampleText { get; set; }
}

This serializes fine:

<example>
    <exampleText>Some text</exampleText>
</example>

The wrapper:

[XmlRoot("examples")]
public class ExampleWrapper : ICollection<Example>
{
    [XmlElement("example")]
    public List<Example> innerList;

    //Implementation of ICollection using innerList
}

This however capitalizes the wrapped Examples for some reason, I tried to override it with XmlElement but this doesn't seem to have the desired effect:

<examples>
    <Example>
        <exampleText>Some text</exampleText>
    </Example>
    <Example>
        <exampleText>Another text</exampleText>
    </Example>
</examples>

Who can tell me what I am doing wrong or if there is an easier way?


Solution

  • The problem is that XmlSerializer has built-in handling for collection types, meaning it it will ignore all your properties and fields (including innerList) if your type happens to implement ICollection and will just serialize it according to its own rules. However, you can customize the name of the element it uses for the collection items with the XmlType attribute (as opposed to the XmlRoot that you had used in your example):

    [XmlType("example")]
    public class Example
    {
        [XmlElement("exampleText")]
        public string ExampleText { get; set; }
    }
    

    That will have the desired serialization.

    See http://msdn.microsoft.com/en-us/library/ms950721.aspx, specifically the answer to the question "Why aren't all properties of collection classes serialized?"