3

I have a class that is inherited from List<T> and also has some properties, like this:

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

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

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

The problem is, serializer sees my list as a collection; the resulting XML contians only list elements, but not class properties (FinalDropCount in this case). This is an example of outputted 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>

Is there some way to save both list contents and properties without resorting to implementing IXmlSerializable by hand?

2
  • Why do you want to serialize the properties? Usually what interests you is the data contained in the class, aka the current values all the variables have. Properties are just a way to access those values. Can you clarify? Commented Feb 24, 2010 at 15:00
  • These properties are part of the data. Think of it this way: DropList is a list of DropItems with some attached data, like FinalDropCount. So, I need to save and load all of the data - both list and properties. Commented Feb 26, 2010 at 4:23

1 Answer 1

2

You have other alternatives that you can consider.

Alternative one - Move to composition instead of inheritance:

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

Alternative two - Move the properties outside the collection:

public class DropList : List<DropItem>
{
}

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

    [XmlAttribute]
    public int FinalDropCount { get; set; }
}
Sign up to request clarification or add additional context in comments.

1 Comment

That's what I am doing now. But semantically it is better to have a DropList that is a List - if that is at all possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.