Does the element name really change per level? If not, you can use a very simple class model and XmlSerializer
. Implementing IXmlSerializable
is... tricky; and error-prone. Avoid it unless you absolutely have to use it.
If the names are different but rigid, I'd just run it through xsd:
xsd example.xml
xsd example.xsd /classes
For an XmlSerializer
without IXmlSerializable
example (same names at each level):
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
[XmlRoot("Foolist")]
public class Record
{
public Record(string name)
: this()
{
Name = name;
}
public Record() { Children = new List<Record>(); }
[XmlAttribute("name")]
public string Name { get; set; }
[XmlElement("Child")]
public List<Record> Children { get; set; }
}
static class Program
{
static void Main()
{
Record root = new Record {
Children = {
new Record("A") {
Children = {
new Record("Child 1"),
new Record("Child 2"),
}
}, new Record("B"),
new Record("C") {
Children = {
new Record("Child 1") {
Children = {
new Record("Little 1")
}
}
}
}}
};
var ser = new XmlSerializer(typeof(Record));
ser.Serialize(Console.Out, root);
}
}