views:

91

answers:

2

Hi I have a class that I want to serialize to xml. The class looks like the following

[XmlRoot("clubMember")]
public class Person
{
   [XmlElement("memberName")]
    public string Name {get; set;}

    [XmlArray("memberPoints")]
    [XmlArrayItem("point")]
    public List<Int32> ClubPoints {get; set;}
}

When I serialize the above class, it generates the following xml

<clubMember>
  <memberName> xxxx</memberName>
  <memberPoints> 
     <point >xx </point>
     <point >xx </point>
  </memberPoints>
</clubMember>

I want to generate xml like the following:

<clubMember>
  <memberName> xxxx</memberName>
  <memberPoints> 
     <point value="xx"/>
     <point value="xx"/>
  </memberPoints>
</clubMember>

is there a way to generate the xml mentioned above,without modifying the class structure? I really like to keep the calss structure intact, because it is used everywhere in my application.

+5  A: 

I don't think this is possible with List<int>. You could define a class Point instead:

[XmlRoot("clubMember")]
public class Person
{
    [XmlElement("memberName")]
    public string Name { get; set; }

    [XmlArray("memberPoints")]
    [XmlArrayItem("point")]
    public List<Point> ClubPoints { get; set; }
}

public class Point
{
    [XmlAttribute("value")]
    public int Value { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var member = new Person
        {
            Name = "Name",
            ClubPoints = new List<Point>(new[] 
            { 
                new Point { Value = 1 }, 
                new Point { Value = 2 }, 
                new Point { Value = 3 } 
            })
        };
        var serializer = new XmlSerializer(member.GetType());
        serializer.Serialize(Console.Out, member);
    }
}
Darin Dimitrov
This is what I would have suggested.
Nat Ryall
Thanks a lotI was trying to avoid modifying the class structure, though
gkar
A: 

I think the only way you could do that is by implementing IXmlSerializable by hand.

Sam Saffron