How to not serialize an object based on a property's value?

后端 未结 2 1410
暖寄归人
暖寄归人 2021-01-23 11:23

If the tags didn\'t give it away, I\'m working with C#\'s XmlSerializer class.

Say, for example, I have a Person class with various properties including age (int), name

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-23 12:09

    Assuming that you have following type of Class structure(As you specified in the comment)

    public class Person 
    {
        public int Age { get; set; }
    
        public string Name { get; set; }
    
        public bool Deceased { get; set; }
    }
    
    public class Being
    {
        public string Data { get; set; }
    
        [XmlElement("Human")]
        public Person Human { get; set; }
    
        public bool ShouldSerializeHuman()
        {
            return !this.Human.Deceased;
        }
    }
    

    Here I have added a method called ShouldSerialize this is called a pattern for XML serialization. Here you can use XmlArray and XmlArrayItem for lists etc.(With given name) then the ShouldSerialize checks if it can be serialized.

    Below is the code I used for testing.

        private static void Main(string[] args)
        {
            var livingHuman = new Person() { Age = 1, Name = "John Doe", Deceased = true };
            var deadHuman = new Person() { Age = 1, Name = "John Doe", Deceased = false };
    
            XmlSerializer serializer = new XmlSerializer(typeof(Being));
    
            serializer.Serialize(Console.Out, new Being { Human = livingHuman, Data = "new" });
    
            serializer.Serialize(Console.Out, new Being { Human = deadHuman, Data = "old" });
        }
    

    And here's the output: enter image description here

    =============================

    Update:

    If you have list of Person as Humans:

    public class Being
    {
        // [XmlAttribute]
        public string Data { get; set; }
    
        // Here add the following attributes to the property
        [XmlArray("Humans")]
        [XmlArrayItem("Human")]
        public List Humans { get; set; }
    
        public bool ShouldSerializeHumans()
        {
            this.Humans = this.Humans.Where(x => !x.Deceased).ToList();
            return true;
        }
    }
    

    Sample Test:

        private static void Main(string[] args)
        {
            var livingHuman = new Person() { Age = 1, Name = "John Doe", Deceased = true };
            var deadHuman = new Person() { Age = 1, Name = "John Doe", Deceased = false };
    
            var humans = new List { livingHuman, deadHuman };
            XmlSerializer serializer = new XmlSerializer(typeof(Being));
    
            serializer.Serialize(Console.Out, new Being() { Humans = humans, Data = "some other data" });
        }
    

    Output: enter image description here

提交回复
热议问题