是否有一个属性可以跳过C#的xml序列化中的空数组? [英] Is there an attribute to skip empty arrays in the xml-serialization of c#?

查看:202
本文介绍了是否有一个属性可以跳过C#的xml序列化中的空数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#的xml序列化中是否有一个属性可以跳过空数组?这将提高xml输出的可读性.

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

推荐答案

好吧,您也许可以添加ShouldSerializeFoo()方法:

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

识别出ShouldSerialize{name}模式,并调用该方法以查看是否在序列化中包括该属性.还有一个替代的{name}Specified模式,允许您在反序列化(通过设置器)时也检测事物:

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
}

这篇关于是否有一个属性可以跳过C#的xml序列化中的空数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆