3

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.

2 Answers 2

6

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);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is what I would have suggested.
Thanks a lot I was trying to avoid modifying the class structure, though
0

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

Comments

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.