【问题标题】:Recursive Serialization in C#C#中的递归序列化
【发布时间】:2015-09-06 19:45:45
【问题描述】:

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

枚举.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
    }

【问题讨论】:

标签: c# recursion xml-serialization


【解决方案1】:

要使用循环引用序列化对象,您需要使用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); 
}

【讨论】:

  • test.xml 只包含:&lt;ArrayOfPERSON xmlns="http://schemas.datacontract.org/2004/07/WindowsFormsApplication1" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"/&gt;
  • 两者都不是,结果相同。
猜你喜欢
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 2019-07-08
  • 1970-01-01
  • 2010-12-01
  • 1970-01-01
  • 2016-04-03
  • 2016-02-26
相关资源
最近更新 更多