C# 列表中每个项上的条件序列化

C# 列表中每个项上的条件序列化,c#,xml-serialization,conditional,C#,Xml Serialization,Conditional,我想控制列表中每一项的Xml序列化,假设您有: public class Item { [XmlElement("id")] public int Id { get; set; } [XmlElement("label")] public string Label { get; set; } #region Conditional serialization public bool ShouldSerializeLabe

我想控制列表中每一项的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.IsNullOrEmptyLabel中的项
是否不应在我的集合中序列化?我的解决方法是在序列化之前清理项目列表,但是有没有一种方法可以声明性地执行此操作?

编写您自己的xml序列化程序。您可以使用IXmlSerializable接口
或者,您可以编写自己的ToXml方法来输出字符串。有很多方法可以做到这一点,但编写自己的方法可以满足您的需要。

您应该研究在类上实现IXmlSerializable,并进行自定义序列化/反序列化,以便跳过该项。XmlSerializer的语言中没有用于执行此操作的条件属性。另一个选项是循环项目集合并忽略带有空标签的项目。第二个选项是我当前的解决方法:在某个点上你是对的。我添加了以下内容:public void writexmlwriter writer{if!string.IsNullOrEmptyLabel{writer.WriteElementStringid,Id;writer.WriteElementStringlabel,Label;}}虽然它适用于我的集合,但也意味着没有标签的单个项将不再序列化。因此,使用IXmlSerializable具有全局影响,这是我不希望看到的