How to make a value type nullable with .NET XmlSerializer?

前端 未结 7 522
陌清茗
陌清茗 2020-12-02 11:47

Let\'s suppose I have this object:

[Serializable]
public class MyClass
{
    public int Age { get; set; }
    public int MyClassB { get; set; }
}
[Serializab         


        
7条回答
  •  臣服心动
    2020-12-02 12:09

    I just discovered this. XmlSerialier looks for a XXXSpecified boolean property to determine if it should be included. This should solve the problem nicely.

    [Serializable]
    public class MyClass
    {
      public int Age { get; set; }
      [XmlIgnore]
      public bool AgeSpecified { get { return Age >= 0; } }
      public int MyClassB { get; set; }
    }
    
    [Serializable]
    public class MyClassB
    {
      public int RandomNumber { get; set; }
    }
    

    Proof:

    static string Serialize(T obj)
    {
      var serializer = new XmlSerializer(typeof(T));
      var builder = new StringBuilder();
      using (var writer = new StringWriter(builder))
      {
        serializer.Serialize(writer, obj);
        return builder.ToString();
      }
    }
    
    static void Main(string[] args)
    {
      var withoutAge = new MyClass() { Age = -1 };
      var withAge = new MyClass() { Age = 20 };
    
      Serialize(withoutAge); // = 0
      Serialize(withAge); // = 200
    }
    

    Edit: Yes, it is a documented feature. See the MSDN entry for XmlSerializer

    Another option is to use a special pattern to create a Boolean field recognized by the XmlSerializer, and to apply the XmlIgnoreAttribute to the field. The pattern is created in the form of propertyNameSpecified. For example, if there is a field named "MyFirstName" you would also create a field named "MyFirstNameSpecified" that instructs the XmlSerializer whether to generate the XML element named "MyFirstName".

提交回复
热议问题