2

I'm trying to create a class that can be serialized into XML via the XMLSerializer.

Destination XML should look something like this

<subject_datas type="array">
    <subject_data>
           ...
    </subject_data>
    <subject_data>
           ...
    </subject_data>
</subject_datas>

The problem is the type attribute for the subject_datas tag. What i tried was to design it as a derived List and attach a property with a XMLAttribute attribute like this

[XmlRoot(ElementName = "subject_datas")]
public class SubjectDatas : List<SubjectData>
{
    public SubjectDatas (IEnumerable<SubjectData> source)
    {
        this.AddRange(source);
        Type = "array";
    }

    [XmlAttribute(AttributeName = "type")]
    public string Type { get; set; }
}

But because the class is a Collection the XMLSerializer will just serialize the objects in the Collection not the Collection itself. So my Type property gets ignored :(

Ralf
  • 1,216
  • 10
  • 20

1 Answers1

5

You could use composition over inheritance

    [XmlRoot(ElementName = "subject_datas")]
    public class SubjectDatas
    {
        [XmlElement(ElementName = "subject_data")]
        public List<SubjectData> SubjectDatas2 { get; set; }

        public SubjectDatas(IEnumerable<SubjectData> source)
        {
            SubjectDatas2= new List<SubjectData>();
            this.SubjectDatas2.AddRange(source);
            Type = "array";
        }

        private SubjectDatas()
        {
            Type = "array";
        } 

        [XmlAttribute(AttributeName = "type")]
        public string Type { get; set; }
    }
dan
  • 198
  • 7
  • 1
    I was somehow under the impression that this would give me another tag between subject_datas and subject_data for the List. But it doesn't. Accepted as correct answer. – Ralf Sep 11 '13 at 18:05
  • The drawback to this is that you have to manually implement routing between the various IList public members in SubjectDatas2 and SubjectDatas if you want SubjectDatas to still function in code the same way, without having to go through and add in a .SubjectDatas2 everywhere you reference it as a list. – Thought Sep 08 '14 at 17:58