[英]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: 例如,带有检查清单的Student对象:
[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. 我的目标是序列化Student模型,并仅将满足某些条件的考试纳入XML中,例如,我只希望分数(<5)低的考试。
Can this kind of operation be done using XmlSerializer present into System.Xml.Serialization
namespace? 可以使用
System.Xml.Serialization
命名空间中存在的XmlSerializer来完成这种操作吗?
You can simply create a student with satisfying exams score using a LINQ query and then serialize the result 您可以使用LINQ查询简单地创建一个具有令人满意的考试成绩的学生,然后序列化结果
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?). 更复杂的方法是编写某种自定义的
IList<Exam>
填充程序,它包装相同的List<Exam>
实例并应用过滤,但是...这很丑陋,我强烈建议您不要尝试这样做(问题,例如:如果在包装类型上调用Add
,并且所添加的元素得分较高,会发生什么?)。
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. 因此,我的建议是在序列化之前进行过滤-通过删除不需要的项或通过仅创建所需项的克隆来进行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.