Search code examples
c#xmlserializerhighrise

XMLSerializer and creating an XML Array with an attribute


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 :(


Solution

  • 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; }
        }