Serialize Property as Xml Attribute in Element

后端 未结 2 1015
一整个雨季
一整个雨季 2020-11-27 12:35

I have the following class:

[Serializable]
public class SomeModel
{
    [XmlElement(\"SomeStringElementName\")]
    public string SomeString { get; set; }

          


        
2条回答
  •  萌比男神i
    2020-11-27 12:43

    Kind of, use the XmlAttribute instead of XmlElement, but it won't look like what you want. It will look like the following:

     
     
    

    The only way I can think of to achieve what you want (natively) would be to have properties pointing to objects named SomeStringElementName and SomeInfoElementName where the class contained a single getter named "value". You could take this one step further and use DataContractSerializer so that the wrapper classes can be private. XmlSerializer won't read private properties.

    // TODO: make the class generic so that an int or string can be used.
    [Serializable]  
    public class SerializationClass
    {
        public SerializationClass(string value)
        {
            this.Value = value;
        }
    
        [XmlAttribute("value")]
        public string Value { get; }
    }
    
    
    [Serializable]                     
    public class SomeModel                     
    {                     
        [XmlIgnore]                     
        public string SomeString { get; set; }                     
    
        [XmlIgnore]                      
        public int SomeInfo { get; set; }  
    
        [XmlElement]
        public SerializationClass SomeStringElementName
        {
            get { return new SerializationClass(this.SomeString); }
        }               
    }
    

提交回复
热议问题