Luke
Luke

Reputation: 1258

Naming a List<T> element for XML serialization

I'm trying to serialize a class to XML and I can't get the result I want for a sub element where the property is just a List. (C#, .Net4.5, trying in WinForms)

My example is as follows:

[Serializable]
public class Model
{
    public string element = "elTest";
    public List<String> roles;
}

Which I write out to XML

    private void button2_Click(object sender, EventArgs e)
    {
        var me = new Model();
        me.roles = new List<string>()
        {
            "testString"
        };
        var ser = new XmlSerializer(typeof(OtherModel));
        using (var sw = new StreamWriter("C:\\temp\\test123.xml"))
        {
            ser.Serialize(sw, me);
        }
    }

And that gives me the output like:

 <element>elTest</element>
  <roles>
    <string>testString</string>
  </roles>

How do I get it so that

<string>

in this example shows up as

<role>

I've tried creating another class Role whit its own property and making a List but then I get something like

  <roles>
    <Role>
      <myRole>theRole</myRole>

Which isn't what I want.

Thanks.

Upvotes: 0

Views: 84

Answers (2)

Amit Kumar Ghosh
Amit Kumar Ghosh

Reputation: 3726

Exactly XmlArrayItem solves your problem.

Upvotes: 0

FoggyFinder
FoggyFinder

Reputation: 2220

Need to use the attribute XmlArrayItem

https://msdn.microsoft.com/en-us/library/vstudio/2baksw0z(v=vs.100).aspx

[Serializable]
public class Model
    {
        public string element = "elTest";
        [XmlArrayItem("role")]
        public List<String> roles;
    }
    class Program
    {
        static void Main(string[] args)
        {
            var me = new Model();
            me.roles = new List<string>()
        {
            "testString"
        };
            var ser = new XmlSerializer(me.GetType());
            using (var sw = new StreamWriter("0.xml"))
            {
                ser.Serialize(sw, me);
            }

            Console.ReadKey(true);
        }
}

Save as:

<?xml version="1.0" encoding="utf-8"?>
<Model xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <element>elTest</element>
  <roles>
    <role>testString</role>
  </roles>
</Model>

Upvotes: 3

Related Questions