Add Xml Attribute to string property

前端 未结 2 886
春和景丽
春和景丽 2020-12-06 19:00

I have a custom object which has a string property called \'Name\' I\'d like to keep the XML generated by serialization the same but add an attribute to the element called \

2条回答
  •  心在旅途
    2020-12-06 19:24

    It is possible if you define another type as below:

    public class Person
    {
    
        private string _name;
    
    
        [XmlIgnore]
        public string Name
        {
            get
            {
                return _name;
            }
            set
            {
                _name = value;
                ThePersonName = new PersonName()
                                    {
                                        Name = FullName,
                                        NiceName = _name
                                    };
            }
        }
    
        [XmlElement(ElementName = "Name")]
        public PersonName ThePersonName { get; set; }
    
        public string FullName { get; set; }
    
    }
    
    public class PersonName
    {
        [XmlAttribute]
        public string NiceName { get; set; }
    
        [XmlText]
        public string Name { get; set; }
    }
    

    Using

            XmlSerializer s = new XmlSerializer(typeof(Person));
            Person ali = new Person();
            ali.FullName = "Ali Kheyrollahi";
            ali.Name = "Nobody";
            s.Serialize(new FileStream("ali.xml",FileMode.Create), ali);
    

    Will generate

    
    
      Ali Kheyrollahi
      Ali Kheyrollahi
    
    

提交回复
热议问题