Serializing a Nullable in to XML

后端 未结 5 632
灰色年华
灰色年华 2020-12-02 22:34

I am trying to serialize a class several of the data-members are Nullable objects, here is a example

[XmlAttribute(\"AccountExpirationDate\")]
public Nullabl         


        
5条回答
  •  离开以前
    2020-12-02 23:27

    Define a Serializable that encapsulates your funcionality.

    Here's are and example.

    [XmlAttribute("AccountExpirationDate")]  
    public SerDateTime AccountExpirationDate   
    {   
      get { return _SerDateTime ; }   
      set { _SerDateTime = value; }   
    }  
    
    
    /// 
    /// Serialize DateTime Class (yyyy-mm-dd)
    /// 
    public class SerDateTime : IXmlSerializable {
        /// 
        /// Default Constructor when time is not avalaible
        /// 
        public SerDateTime() { }
        /// 
        /// Default Constructor when time is avalaible
        /// 
        /// 
        public SerDateTime(DateTime pDateTime) {
            DateTimeValue = pDateTime;
        }
    
        private DateTime? _DateTimeValue;
        /// 
        /// Value
        /// 
        public DateTime? DateTimeValue {
            get { return _DateTimeValue; }
            set { _DateTimeValue = value; }
        }
    
        // Xml Serialization Infrastructure
        void IXmlSerializable.WriteXml(XmlWriter writer) {
            if (DateTimeValue == null) {
                writer.WriteString(String.Empty);
            } else {
                writer.WriteString(DateTimeValue.Value.ToString("yyyy-MM-dd"));
                //writer.WriteString(SerializeObject.SerializeInternal(DateTimeValue.Value));
            }
        }
    
        void IXmlSerializable.ReadXml(XmlReader reader) {
            reader.ReadStartElement();
            String ltValue = reader.ReadString();
            reader.ReadEndElement();
            if (ltValue.Length == 0) {
                DateTimeValue = null;
            } else {                
                //Solo se admite yyyyMMdd
                //DateTimeValue = (DateTime)SerializeObject.Deserialize(typeof(DateTime), ltValue);
                DateTimeValue = new DateTime(Int32.Parse(ltValue.Substring(0, 4)),
                                    Int32.Parse(ltValue.Substring(5, 2)),
                                    Int32.Parse(ltValue.Substring(8, 2)));                                    
            }
        }
    
        XmlSchema IXmlSerializable.GetSchema() {
            return (null);
        }
    }
    #endregion
    

提交回复
热议问题