【发布时间】:2010-09-27 16:20:38
【问题描述】:
在c#的xml序列化中是否有跳过空数组的属性?这将提高 xml 输出的可读性。
【问题讨论】:
标签: c# xml arrays serialization xml-serialization
在c#的xml序列化中是否有跳过空数组的属性?这将提高 xml 输出的可读性。
【问题讨论】:
标签: c# xml arrays serialization xml-serialization
好吧,你或许可以添加一个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
}
【讨论】: