【问题标题】:Is there an attribute to skip empty arrays in the xml-serialization of c#?在 c# 的 xml 序列化中是否有一个属性可以跳过空数组?
【发布时间】:2010-09-27 16:20:38
【问题描述】:

在c#的xml序列化中是否有跳过空数组的属性?这将提高 xml 输出的可读性。

【问题讨论】:

    标签: c# xml arrays serialization xml-serialization


    【解决方案1】:

    好吧,你或许可以添加一个ShouldSerializeFoo() 方法:

    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);
        }
    }
    

    ShouldSerialize{name}模式被识别,调用该方法查看是否在序列化中包含该属性。还有另一种 {name}Specified 模式,它允许您在反序列化时(通过 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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-19
      相关资源
      最近更新 更多