![](/img/trans.png)
[英]C# Xml Serialization: Serialize Class properties as attributes to the parent class
[英]How to serialize xml array AND class properties using C# XML serialization
我有一个继承自List<T>
,还有一些属性,如下所示:
[Serializable]
public class DropList : List<DropItem>
{
[XmlAttribute]
public int FinalDropCount{get; set;}
}
此类作为更大类的一部分序列化为xml:
[Serializable]
public class Location
{
public DropList DropList{get; set;}
....
}
问题是,序列化程序将我的列表视为集合; 生成的XML只包含列表元素,但不包括类属性(在本例中为FinalDropCount)。 这是输出XML的示例:
<Location xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<DropList>
<DropItem ProtoId="3" Count="0" Minimum="0" Maximum="0" />
<DropItem ProtoId="4" Count="0" Minimum="0" Maximum="0" />
</DropList>
....
</Location>
是否有某种方式来节省列表的内容和属性,而不诉诸实施IXmlSerializable
手?
您还可以考虑其他替代方案。
另一种 - 移动到合成而不是继承:
public class DropInfo
{
[XmlArray("Drops")]
[XmlArrayItem("DropItem")]
public List<DropItem> Items { get; set; }
[XmlAttribute]
public int FinalDropCount { get; set; }
}
public class Location
{
public DropInfo DropInfo { get; set; }
}
备选方案二 - 移动集合外的属性:
public class DropList : List<DropItem>
{
}
public class Location
{
public DropList DropList { get; set; }
[XmlAttribute]
public int FinalDropCount { get; set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.