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


你可以使用构造而不是继承

    [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; }
    }
链接地址: http://www.djcxy.com/p/65142.html

上一篇: c#XML序列化如何使用xsi序列化平面列表:nil =“true”

下一篇: XMLSerializer并创建一个具有属性的XML Array