簡體   English   中英

如何使用C#XML序列化序列化xml數組和類屬性

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM