Serialize a generic collection specifying element names for items in the collection

♀尐吖头ヾ 提交于 2019-12-25 04:49:07

问题


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>

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/2826296/serialize-a-generic-collection-specifying-element-names-for-items-in-the-collect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!