Eoin Melly
Eoin Melly

Reputation: 11

Add XmlAttribute to C# Class for serialization

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.

Upvotes: 1

Views: 1929

Answers (2)

The One
The One

Reputation: 4706

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>

Upvotes: 1

Yuriy Gavriluk
Yuriy Gavriluk

Reputation: 104

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.

Upvotes: 0

Related Questions