[英]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. 我正在尝试创建一个可以通过XMLSerializer序列化为XML的类。
Destination XML should look something like this 目标XML应该看起来像这样
<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. 问题是subject_datas标记的type属性。 What i tried was to design it as a derived List and attach a property with a XMLAttribute attribute like this
我试图将其设计为派生列表,并使用XMLAttribute属性附加属性,如下所示
[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. 但是因为该类是一个Collection,所以XMLSerializer只会序列化Collection中的对象,而不是Collection本身。 So my Type property gets ignored :(
所以我的Type属性被忽略了:(
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; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.