How to serialize xml array and class properties using C # XML serialization

I have a class that inherits from List<T>, and also has some properties, for example:

[Serializable]
public class DropList : List<DropItem>
{
    [XmlAttribute]
    public int FinalDropCount{get; set;}
}

This class is serialized in xml as part of a larger class:

[Serializable]
public class Location
{
    public DropList DropList{get; set;}
    ....
}

The problem is that the serializer sees my list as a collection; as a result, XML contains only list items, but not class properties (FinalDropCount in this case). This is an example of XML output:

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

Is there a way to save both the contents of the list and the properties without resorting to IXmlSerializablemanual use ?

+3
source share
1 answer

You have other alternatives that you may consider.

- :

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; }
}

2 - :

public class DropList : List<DropItem>
{
}

public class Location
{
    public DropList DropList { get; set; }

    [XmlAttribute]
    public int FinalDropCount { get; set; }
}
+2

Source: https://habr.com/ru/post/1734236/


All Articles