I am trying to serialize a class several of the data-members are Nullable objects, here is a example
[XmlAttribute("AccountExpirationDate")] public Nullable<DateTime> AccountExpirationDate { get { return userPrincipal.AccountExpirationDate; } set { userPrincipal.AccountExpirationDate = value; } }
However at runtime I get the error
Cannot serialize member 'AccountExpirationDate' of type System.Nullable`1[System.DateTime]. XmlAttribute/XmlText cannot be used to encode complex types.
However I checked and Nullable is a SerializableAttribute. What am I doing wrong?
XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.
For serializing, you can use the DateTime(Offset). ToString method in your converter write logic. This allows you to write DateTime and DateTimeOffset values using any of the standard date and time formats, and the custom date and time formats.
C# Nullable DateTimeDateTime is a Value Type like int, double etc. so there is no way to assigned a null value. if(date == null) //WRONG.
Xml. Serialization namespace) class is used to serialize and deserialize. The class method Serialize is called. Since we have to serialize in a file, we create a " TextWriter ".
If you just want it to work, then perhaps:
using System; using System.ComponentModel; using System.Xml.Serialization; public class Account { // your main property; TODO: your version [XmlIgnore] public Nullable<DateTime> AccountExpirationDate {get;set;} // this is a shim property that we use to provide the serialization [XmlAttribute("AccountExpirationDate")] [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public DateTime AccountExpirationDateSerialized { get {return AccountExpirationDate.Value;} set {AccountExpirationDate = value;} } // and here we turn serialization of the value on/off per the value [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeAccountExpirationDateSerialized() { return AccountExpirationDate.HasValue; } // test it... static void Main() { var ser = new XmlSerializer(typeof(Account)); var obj1 = new Account { AccountExpirationDate = DateTime.Today }; ser.Serialize(Console.Out, obj1); Console.WriteLine(); var obj2 = new Account { AccountExpirationDate = null}; ser.Serialize(Console.Out, obj2); } }
This will only include the attribute when there is a non-null value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With