c#のxml-serializationで空の配列をスキップする属性はありますか?これにより、xml-outputの人間が読みやすくなります。
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 に答える