Có thuộc tính nào để bỏ qua các mảng trống trong xml-serialization của C# không? Điều này sẽ làm tăng khả năng đọc của xml-output của con người.Có thuộc tính nào để bỏ qua các mảng trống trong xml-serialization của C# không?
8
A
Trả lời
17
Vâng, bạn có lẽ có thể thêm một phương pháp 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);
}
}
Các ShouldSerialize{name}
guốc được công nhận, và phương pháp này được gọi là để xem liệu có bao gồm tài sản trong serialization. Ngoài ra còn có một mẫu {name}Specified
thay thế cho phép bạn cũng phát hiện ra những thứ khi deserializing (thông qua 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
}