0

I have a simple class derived from a generic list of string as follows:

[Serializable]
[System.Xml.Serialization.XmlRoot("TestItems")]
public class TemplateRoleCollection : List<string>
{

}

when I serialize this, I get the following XML:

<TestItems>
  <string>cat</string>
  <string>dog</string>
  <string>wolf</string>
</TestItems>

Is there any way to override the xml element name which is used for serializing items in the collection? I would like the following xml to be produced:

<TestItems>
  <TestItem>cat</TestItem>
  <TestItem>dog</TestItem>
  <TestItem>wolf</TestItem>
</TestItems>
Matthew Dresser
  • 11,273
  • 11
  • 76
  • 120

2 Answers2

3

You don't specify this at the class level, you specify it at the property level and use the XmlArrayItemAttribute:

public class ContainerClass
{
    [XmlArray("TestItems")]
    [XmlArrayItem("TestItem")]
    public List<string> TemplateRoles { get; set; }
}

Also note that [Serializable] has no effect on XML serialization, it is used for binary or DataContract serialization.

Aaronaught
  • 120,909
  • 25
  • 266
  • 342
  • I just ran into this problem. Is there any way to do this and still inherit from a list? This answer works fine, but is a workaround rather than the solution I was looking for. In my case it's a List of a custom (non-primitive) type, which is already marked with [XmlRoot] attribute, so I was surprised when the serializer didn't respect this for a class of List. – si618 Sep 01 '10 at 02:53
  • @Si: The `XmlRootAttribute` doesn't do what you appear to believe it does. It only controls the name of the root element (AKA document element) when you serialize the class on its own. Perhaps you are looking for the `XmlTypeAttribute`? – Aaronaught Sep 01 '10 at 14:33
0

The answer given did not always work for me as I needed to inherit directly from List. I posted a similar question and got directed to this answer Change XmlElement name for XML serialisation which allows you to do that.

Community
  • 1
  • 1
Matthew Bierman
  • 360
  • 3
  • 12