我想在一個列表上的每個項目來控制XML序列化的每一項有條件的序列化,假設你有這樣的:在列表
public class Item {
[XmlElement("id")]
public int Id { get; set; }
[XmlElement("label")]
public string Label { get; set; }
#region Conditional serialization
public bool ShouldSerializeLabel()
{
return !string.IsNullOrEmpty(Label);
}
#endregion
}
public class Root {
[XmlArray("items")]
[XmlArrayItem("item")]
public List<Item> Items { get; set; }
#region Conditional serialization
// Suppose I have two items but one has no label,
// How to avoid this :
// <items>
// <item>
// <id>5</id>
// <label>5</label>
// </item>
// <item> // I don't want items without label in my collection, how to tell the XmlSerializer not to serialize them
// <id>4</id>
// </item>
// </items>
//
// But I still want to have to possibility to do that :
// <product>
// <item> // this item has no label and it's ok
// <id>42</id>
// </item>
// <price>1.99</price>
// </product>
#endregion
}
如何判斷與string.IsNullOrEmpty一個項目(標籤) 不應該在我的收藏中序列化?我的解決方法是在序列化之前清理Item的列表,但有沒有辦法以聲明方式執行此操作?
您應該考慮在您的類上實現IXmlSerializable並執行自定義序列化/反序列化以跳過該項目。 XmlSerializer的語言中沒有條件屬性,它將執行此操作。 另一種選擇是循環播放項目集合並省略具有空標籤的項目。 – 2009-12-24 14:34:22
你的第二個選擇是我目前的解決方法:) – hoang 2009-12-24 14:37:57