C# 的 xml 序列化中是否有一个属性可以跳过空数组?这将提高 xml 输出的可读性。
好吧,你也许可以添加一个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 被识别,并调用该方法以查看是否在序列化中包含该属性。还有一个替代方案{name}Specified
允许您在反序列化时检测事物的模式(通过设置器):
[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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)