Change XmlElement name for XML serialisation

后端 未结 2 506
太阳男子
太阳男子 2021-01-01 19:23

We have the followig code:

[Serializable]
public class Class1
{
    [XmlElement(\"description\")]
    public string Description { get; set; }
}
class Program         


        
相关标签:
2条回答
  • 2021-01-01 19:50

    You can use XmlTypeAttribute.TypeName for this.

    Try this for you Class1 definition

        [XmlType(TypeName = "Item1")]
        [Serializable]
        public class Class1
        {
            [XmlElement("description")]
            public string Description { get; set; }
        }
    
    0 讨论(0)
  • 2021-01-01 19:56

    Use an XmlTypeAttribute on the class as well:

    [XmlType(TypeName="ElementName")]
    [Serializable]
    public class Class1 { ...
    

    EDIT: Updated from XmlRootAttribute to XmlTypeAttribute. The former works where the type being passed to the serialiser is the attributed type (Class1 here), but not when there is a wrapping type (List<Class1> here). That XmlType works is not clear from the documentation (my emphasis):

    Controls the XML schema that is generated when the attribute target is serialized by the XmlSerializer.

    Credit to Bala R's answer.

    0 讨论(0)
提交回复
热议问题