Serializing data using XmlArrayItemAttribute not working well

时间秒杀一切 提交于 2019-12-24 17:02:08

问题


I have this DataContract, which is an array of strings:

[System.Xml.Serialization.XmlArrayAttribute(Order = 19)]
[System.Xml.Serialization.XmlArrayItemAttribute("CardNumber", typeof(string), IsNullable = false)]
[DataMember]
public string[] Cards {get; set; }

As I read, it should be serialized like this:

<Cards>
    <CardNumber>123123</CardNumber>
</Cards>

but I'm still getting:

<Cards>
    <string>123123</string>
</Cards>

What's wrong with it?


回答1:


You can use CollectionDataContract instead. First, create a class:

[CollectionDataContract(ItemName="CardNumber")]
public class CardsList : List<string> { }

And then, replace this line:

[DataMember]
public string[] Cards {get; set; }

By this:

[DataMember(Name="Cards")]
public CardsList Cards {get; set; };

Hope it helps.



来源:https://stackoverflow.com/questions/37586165/serializing-data-using-xmlarrayitemattribute-not-working-well

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!