如何根据属性的值序列化对象?
如果标签没有放弃,我正在使用C#的XmlSerializer类。
比方说,我有一个Person类,它有各种属性,包括age(int),name(string)和deceased(bool)。 有没有办法指定我不想序列化已故标志为真的任何对象?
编辑:我应该指定,但不幸的是由于这种情况我无法真正编辑我的对象列表,因为它是另一个类的成员,这是我实际上正在序列化。 还有其他建议吗?
假设您有以下类型的类结构(如您在注释中指定的那样)
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; } }
在这里,我添加了一个名为ShouldSerialize
的方法,这称为XML序列化模式。 在这里你可以使用XmlArray
和XmlArrayItem
作为列表等(使用给定的名称)然后ShouldSerialize
检查它是否可以序列化。
下面是我用于测试的代码。
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" }); }
这是输出:
=============================
更新:
如果你有人类列表作为人类:
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; } }
样品测试:
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" }); }
输出:
如果您有一个Person
对象列表,并且只想序列化其中一些对象,那么只需过滤掉您不需要的对象。 例如:
List people = GetPeople(); //from somewhere List filteredPeople = people.Where(p => !p.Deceased);
现在你只需要序列化filteredPeople
。