每个级别的元素名称真的会改变吗?如果没有,您可以使用非常简单的类模型和XmlSerializer
. 实施IXmlSerializable
是……棘手的;并且容易出错。除非您绝对必须使用它,否则请避免使用它。
如果名称不同但严格,我只需通过 xsd 运行它:
xsd example.xml
xsd example.xsd /classes
对于XmlSerializer
没有IXmlSerializable
示例(每个级别的名称相同):
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);
}
}