c#的xml序列化中是否有跳过空数组的属性?这将增加 xml 输出的可读性。
问问题
3771 次
1 回答
19
好吧,您也许可以添加一个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
模式允许您在反序列化时也检测事物(通过设置器):
[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
}
于 2008-12-19T08:52:01.780 回答