XML segmentation in .NET.

I have a class that I want to serialize in xml. The class is as follows

[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 as follows:

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

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

+3
source share
2 answers

I think the only way to do this is to implement IXmlSerializable manually.

0
source

, List<int>. Point:

[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);
    }
}
+6

Source: https://habr.com/ru/post/1723099/


All Articles