1

I'm having a bit of a head scratching moment here, as I think I'm doing this correctly! I need to create an xml file as below, (I've left out the namespace declarations)

<races> <race racename="race one"> <horse> <name>Silver</name> <age>6</name> </horse> </race> </races>

Class races is a collection of class race, and class race is a collection of class horse. Below is the relevant code for race class which I have and is causing the problem (I think at least).

[Serializable]
[XmlType("race")]
public class Race : CollectionBase
{
    private string _raceName;        

    [XmlAttribute("racename")]
    public string RaceName
    {
        get
        {
            return this._raceName;
        }
        set
        {
            this._raceName = value;
        }
    }

I have the xml file building as expected EXCEPT the attribute racename is not being serialized. It is definitely being assigned to the race object before serialization. Any thoughts? I'm obviously missing something somewhere but I'm not sure how I'd even test where it's failing. Any help would be greatly appreciated!

Eoin.

Eoin Melly
  • 11
  • 1
  • possible duplicate of [When a class is inherited from List<>, XmlSerializer doesn't serialize other attributes](http://stackoverflow.com/questions/5069099/when-a-class-is-inherited-from-list-xmlserializer-doesnt-serialize-other-att) – The One Mar 28 '15 at 15:42

2 Answers2

1

In classes that implement IEnumerable, only collections are serialized, not public properties.

Use the Horse collection inside the Race class and remove :CollectionBase

[Serializable]
[XmlType("race")]
public class Race
{
    [XmlElement("horse")]
  public  List<Horse> Horses { get; set; }


    [XmlAttribute("racename")]
    public string RaceName
    {
        get;

        set;

    }
    public Race()
    {
        Horses = new List<Horse>();
    }
}

Result

<race xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" racename="race one">
 <horse>
  <Name>Silver</Name>
  <Age>6</Age>
 </horse>
</race>
The One
  • 3,729
  • 5
  • 27
  • 44
  • Thanks JAT, I found out afterwards that xmlserializer does indeed ignore properties in classes which inherit from collectionbase. I eventually created a datacontainer class to hold the race object and passed it the racename property as well, as I need each race to also be held within a races collection! Races is the root of the xml file. The datacontainer class is kind of clunky as a solution however, I'm open to any suggestions on a cleaner way to piece this all together! – Eoin Melly Mar 29 '15 at 16:10
0

I suggest you to create a test console application in the solution and test code like this http://pastebin.com/bP340WmR if it works fine create a collections of objects and try to serialize. Doing it step by step will help to understand where exactly the problem is.