How to set the element name programmatically in a list (xml serialization in c#)?

153 Views Asked by At

I have to write some xml files which are all similar and simple(no nested elements, not many attributes), like this:

<example>
  <data1>something1</data1>
  <data2 name="ex">something2</data2>
  <data3>something3</data3>
  ...
</example>

For the moment what I can do is

<example>
  <Data>something1</Data>
  <Data name="ex">something2</Data>
  <Data>something3</Data>
</example>

by using the following classes (I create an Example instance and serialize that)

    [XmlType("example")]
    public class Example : List<Data>
    {}

    public class Data
    {
        [XmlAttribute(AttributeName = "name")]
        public string name { get; set; }

        [XmlText]
        public string data { get; set; }
    }

    Main
    {
        Example ex = new Example();
        ex.Add(new Data() { data = "something1" });
        ex.Add(new Data() { data = "something2", name = "ex" });
        ex.Add(new Data() { data = "something3" });

        string xml = Serialize<Example>(ex); //this only does the serialization
    }

The question is: how can I chance the name of each element ("data1","data2","data3") independently? I know I can set the name for all of them using [XmlArrayItem()] but I want to be able to set each of them differently ex by having a variable inside the class Data that I can set when initializing an element of the list. Is there a way?

0

There are 0 best solutions below