C#中的递归序列化

时间:2015-09-06 19:45:45

标签: c# recursion xml-serialization

我需要将myFamily序列化为.xml文件,我真的不知道该怎么做。

Enums.cs

public enum Genre {
    Male,
    Female
}

PERSON.cs

public class PERSON {
    public string Name { get; set; }
    public Genre Genre { get; set; }
    public List<PERSON> Parents { get; set; }
    public List<PERSON> Children { get; set; }

    public PERSON(string name, Genre genre) {
        this.Name = name;
        this.Genre = genre;
    }
}

Form1.cs的

    private void Form1_Load(object sender, EventArgs e) {
        List<PERSON> myFamily = new List<PERSON>();

        PERSON Andrew = new PERSON("Andrew", Genre.Male);
        PERSON Angela = new PERSON("Angela", Genre.Female);
        PERSON Tina = new PERSON("Tina", Genre.Female);
        PERSON Jason = new PERSON("Jason", Genre.Male);
        PERSON Amanda = new PERSON("Amanda", Genre.Female);
        PERSON Steven = new PERSON("Steven", Genre.Male);

        Andrew.Parents.Add(Tina);
        Andrew.Parents.Add(Jason);

        Angela.Parents.Add(Tina);
        Angela.Parents.Add(Jason);

        Tina.Parents.Add(Amanda);
        Tina.Parents.Add(Steven);

        Jason.Children.Add(Andrew);
        Jason.Children.Add(Angela);

        Tina.Children.Add(Andrew);
        Tina.Children.Add(Angela);

        Amanda.Children.Add(Tina);

        Steven.Children.Add(Tina);

        myFamily.Add(Andrew);
        myFamily.Add(Angela);
        myFamily.Add(Tina);
        myFamily.Add(Jason);
        myFamily.Add(Amanda);
        myFamily.Add(Steven);

        // serialize to an .xml file
    }

1 个答案:

答案 0 :(得分:3)

要使用循环引用序列化对象,您需要使用DataContractSerializer。这样做

  • [DataContract(IsReference=true)]添加到Person
  • [DataMember]添加到您的媒体资源
  • 在构造函数中实例化您的列表
  • 请记住using System.Runtime.Serialization;

所以你的课应该是:

[DataContract(IsReference=true)]
public class PERSON
{
    [DataMember]
    public string Name { get; set; }
    [DataMember]
    public Genre Genre { get; set; }
    [DataMember]
    public List<PERSON> Parents { get; set; }
    [DataMember]
    public List<PERSON> Children { get; set; }

    public PERSON(string name, Genre genre)
    {
        this.Name = name;
        this.Genre = genre;
        Parents = new List<PERSON>();
        Children = new List<PERSON>();
    }
}

序列化:

var serializer = new DataContractSerializer(myFamily.GetType()); 
using (FileStream stream = File.Create(@"D:\Test.Xml")) 
{ 
    serializer.WriteObject(stream, myFamily); 
} 

反序列化:

using (FileStream stream = File.OpenRead(@"D:\Test.Xml"))
{ 
    List<PERSON> data = (List<PERSON>)serializer.ReadObject(stream); 
}