How to exclude null properties when using XmlSerializer

前端 未结 9 1552
谎友^
谎友^ 2021-02-02 07:11

I\'m serializing a class like this

public MyClass
{
    public int? a { get; set; }
    public int? b { get; set; }
    public int? c { get; set; }
}
         


        
9条回答
  •  迷失自我
    2021-02-02 07:55

    The simplest way of writing code like this where the exact output is important is to:

    1. Write an XML Schema describing your exact desired format.
    2. Convert your schema to a class using xsd.exe.
    3. Convert your class back to a schema (using xsd.exe again) and check it against your original schema to make sure that the serializer correctly reproduced every behaviour you want.

    Tweak and repeat until you have working code.

    If you are not sure of the exact data types to use initially, start with step 3 instead of step 1, then tweak.

    IIRC, for your example you will almost certainly end up with Specified properties as you have already described, but having them generated for you sure beats writing them by hand. :-)

提交回复
热议问题