Is there an attribute to skip empty arrays in the xml-serialization of c#?

后端 未结 1 1391
猫巷女王i
猫巷女王i 2021-02-06 05:46

Is there an attribute to skip empty arrays in the xml-serialization of c#? This would increase human-readability of the xml-output.

1条回答
  •  礼貌的吻别
    2021-02-06 06:25

    Well, you could perhaps add a ShouldSerializeFoo() method:

    using System;
    using System.ComponentModel;
    using System.Xml.Serialization;
    [Serializable]
    public class MyEntity
    {
        public string Key { get; set; }
    
        public string[] Items { get; set; }
    
        [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
        public bool ShouldSerializeItems()
        {
            return Items != null && Items.Length > 0;
        }
    }
    
    static class Program
    {
        static void Main()
        {
            MyEntity obj = new MyEntity { Key = "abc", Items = new string[0] };
            XmlSerializer ser = new XmlSerializer(typeof(MyEntity));
            ser.Serialize(Console.Out, obj);
        }
    }
    

    The ShouldSerialize{name} patten is recognised, and the method is called to see whether to include the property in the serialization. There is also an alternative {name}Specified pattern that allows you to also detect things when deserializing (via the setter):

    [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
    [XmlIgnore]
    public bool ItemsSpecified
    {
        get { return Items != null && Items.Length > 0; }
        set { } // could set the default array here if we want
    }
    

    0 讨论(0)
提交回复
热议问题