是否有一个属性可以在c#的xml-serialization中跳过空数组?

Mat*_*ze 8 c# xml arrays serialization xml-serialization

是否有一个属性可以在c#的xml-serialization中跳过空数组?这将增加xml输出的人类可读性.

Mar*_*ell 17

好吧,你也许可以添加一个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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)