如何根据属性的值序列化对象?

时间:2015-06-23 23:19:02

标签: c# xml serialization

如果标签没有放弃,我就使用C#的XmlSerializer类。

比如说,我有一个Person类,它有各种属性,包括age(int),name(string)和deceased(bool)。有没有办法指明我不想序列化已故标志为真的任何对象?

编辑:我应该指定,但不幸的是由于这种情况我无法真正编辑我的对象列表,因为它是另一个类的成员,这是我实际上正在序列化的。还有其他建议吗?

2 个答案:

答案 0 :(得分:4)

  

假设您有以下类型的类结构(正如您在注释中指定的那样)

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序列化模式。在这里,您可以使用XmlArrayXmlArrayItem作为列表等(使用给定名称),然后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" });
    }
  

以下是输出:   enter image description here

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

  

<强>更新

如果你有人的名单作为人类:

public class Being
{
    // [XmlAttribute]
    public string Data { get; set; }

    // Here add the following attributes to the property
    [XmlArray("Humans")]
    [XmlArrayItem("Human")]
    public List<Person> 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<Person> { livingHuman, deadHuman };
        XmlSerializer serializer = new XmlSerializer(typeof(Being));

        serializer.Serialize(Console.Out, new Being() { Humans = humans, Data = "some other data" });
    }
  

输出:   enter image description here

答案 1 :(得分:1)

如果您有Person个对象的列表,并且只想序列化其中一些,那么只需过滤掉您不需要的对象。例如:

List<Person> people = GetPeople(); //from somewhere
List<Person> filteredPeople = people.Where(p => !p.Deceased);

现在您只需要序列化filteredPeople