Changing type of element in XML Serialization

前端 未结 2 947
生来不讨喜
生来不讨喜 2021-01-14 01:15

I am having huge problems with XML serialization. I have two classes, both need to be serializeable. In the inherited class, I would like to change the serialization behavio

2条回答
  •  不思量自难忘°
    2021-01-14 01:50

    You're specifying two different XML elements with the same name on the same graph level, which is not allowed.

    I will offer a solution, but it involves concatenating type and name for the Cat class serialization. If it is not imperative to serialize that NameAndType class, then go on: On Animal, set Name to be virtual; On Cat, set XmlIgnore on Name2. Then override Name and return both properties of Name2 the way you fancy.

    If you really need to serialize that class as it is, then I'm afraid you'll have to so it with a different elementName.

    Edit: Sample code:

    public class Animal
    {
        [XmlElement(ElementName = "NAME")]
        public virtual string Name { get; set; }
    
        public virtual bool ShouldSerializeName() { return true; }
    } 
    
    public class Cat : Animal
    {
        public override bool ShouldSerializeName() { return false; }
    
        [XmlIgnore]
        public NameAndType Name2 { get; set; }
    
        [XmlElement(ElementName = "NAME")]
        public override string Name 
        { 
            get
            {
                return String.Format("{0} [Type:{1}]", Name2.Name, Name2.Type); 
            }
            set { } 
        }        
    }
    

提交回复
热议问题