В пространстве имен System.Xml.Serialization
есть все, что вам нужно. Вот пример того, как может выглядеть ваш класс Matryoshka (требуется всего несколько небольших изменений):
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml.Serialization;
public class Doll //must be public
{
public string Color { get; set; }
public List<Doll> ChildDolls { get; set; } = new List<Doll>();
public Doll() //needs a ctor without parameters
{
Color = "Not set";
}
public Doll(string color)
{
this.Color = color;
} // End of Constructor
public void AddChild(Doll NewChild)
{
this.ChildDolls.Add(NewChild);
} // End of Add Child method
public override string ToString()
{
var output = new StringBuilder();
// Adds the current doll's color
output.AppendLine(Color);
// Adds each doll's children, and each of theirs, and so on...
foreach (Doll Child in this.ChildDolls)
{
output.Append(Child.ToString());
}
return output.ToString();
} // End of To String method
} // End of class
А вот методы сериализации / десериализации:
public static void Serialize(string path, Doll matryoshka)
{
using (var writer = new StreamWriter(path))
{
var s = new XmlSerializer(typeof(Doll));
s.Serialize(writer, matryoshka);
}
}
public static Doll Deserialize(string path)
{
using (var reader = new StreamReader(path))
{
var x = new XmlSerializer(typeof(Doll));
return (Doll)x.Deserialize(reader);
}
}
Использование их довольно просто:
var redDoll = new Doll("red");
var green1Doll = new Doll("green1");
var green2Doll = new Doll("green2");
var blue1Doll = new Doll("blue1");
var blue2Doll = new Doll("blue2");
redDoll.AddChild(green1Doll);
redDoll.AddChild(green2Doll);
green1Doll.AddChild(blue1Doll);
green2Doll.AddChild(blue2Doll);
Serialize("dolls.xml", redDoll);
Результат будет таким:
<?xml version="1.0" encoding="utf-8"?>
<Doll xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Color>red</Color>
<ChildDolls>
<Doll>
<Color>green1</Color>
<ChildDolls>
<Doll>
<Color>blue1</Color>
<ChildDolls />
</Doll>
</ChildDolls>
</Doll>
<Doll>
<Color>green2</Color>
<ChildDolls>
<Doll>
<Color>blue2</Color>
<ChildDolls />
</Doll>
</ChildDolls>
</Doll>
</ChildDolls>
</Doll>
Десериализация тоже работает отлично:
var deserializedDoll = Deserialize("dolls.xml");
Console.Write(deserializedDoll.ToString());
Выход, как и ожидалось, :
red
green1
blue1
green2
blue2
Вы также можете управлять тем, как ваш XML генерируется сериализатором, используя атрибуты. Вот документы