XmlSerializer and nullable attributes

前端 未结 2 2077
情歌与酒
情歌与酒 2021-02-02 08:11

I have a class with numerous Nullable properties which I want to be serializable to XML as attributes. This is apparently a no-no as they are considered \'complex types

相关标签:
2条回答
  • 2021-02-02 08:34

    Implement the IXmlSerializable interface on your class. You can then handle special cases such as nullables in the ReadXML and WriteXML methods. There's a good example in the MSDN documentation page..

     
    class YourClass : IXmlSerializable
    {
        public int? Age
        {
            get { return this.age; }
            set { this.age = value; }
        }
    
        //OTHER CLASS STUFF//
    
        #region IXmlSerializable members
        public void WriteXml (XmlWriter writer)
        {
            if( Age != null )
            {
                writer.WriteValue( Age )
            }
        }
    
        public void ReadXml (XmlReader reader)
        {
            Age = reader.ReadValue();
        }
    
        public XmlSchema GetSchema()
        {
            return(null);
        }
        #endregion
    }
    
    0 讨论(0)
  • 2021-02-02 08:49

    I had a similar problem with some code I was working on, and I decided just to use a string for the property I was serializing and deserializing. I ended up with something like this:

    [XmlAttribute("Age")]
    public string Age
    {
        get 
        { 
            if (this.age.HasValue)
                return this.age.Value.ToString(); 
            else
                return null;
        }
        set 
        { 
            if (value != null)
                this.age = int.Parse(value);
            else
                this.age = null;
        }
    }
    
    [XmlIgnore]
    public int? age;
    
    0 讨论(0)
提交回复
热议问题