简体   繁体   中英

Serialize item in base of condition using XmlSerializer c#

I've an object which has one of its parameters a List of objects.

Example, a Student object with a List of Exams:

[Serializable]
public class Student
{
    [XmlAttribute("Name")]
    public string Name {get; set;}

    [XmlArray("Exams")]
    public List<Exam> Exams {get; set;}
}

[Serializable]
public class Exam
{
    [XmlAttribute("Course")]
    public string Course;

    [XmlAttribute("Score")]
    public int Score;
}

My goal is to serialize the Student model and include into the XML only the Exams satisfying some criteria, example I would like only the Exams with low ( < 5) score.

Can this kind of operation be done using XmlSerializer present into System.Xml.Serialization namespace?

You can simply create a student with satisfying exams score using a LINQ query and then serialize the result

var studentToSerialize = new Student { 
           Name = student.Name,
           Exams = student.Exams.where(e => e.Score < 5)
    }
// Your serialization logic here

I'm not aware of any serializer that offers "per collection element" conditional serialization; some do "per property" conditional serialization, but ... not this. The simplest thing would be to create a copy of the student with just the items you want to serialize. The more complicated approach would be to write some kind of custom IList<Exam> shim that wraps the same List<Exam> instance and applies filtering, but... that's all kinds of ugly, and I strongly recommend not trying to do that (problems, for example: what happens if Add is called on the wrapper type, and the element being added has a high score?).

So my suggestion would be to filter before serializing - either by removing the unwanted items, or by creating a clone with just the desired items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM