我有一个类,它基本上是同一个对象的树结构(每个叶子总是包含相同类型的根)。像这样:
[Serializable]
public class MyClass
{
public string Property1 { get; set; }
public string Property2 { get; set; }
public List<MyClass> Children { get; set; }
public MyClass()
{
Children = new List<MyClass>();
}
public void Serialize(string filename)
{
var serializer = new XmlSerializer(GetType());
using (var sw = new StreamWriter(filename, false, Encoding.UTF8))
serializer.Serialize(sw, this);
}
}
当我创建具有多个子节点的此类的实例来测试Serialize()函数时,XML中的Children节点始终为空。为什么呢?
以下是初始化的示例:
var test = new MyClass {Property1 = "test"};
test.Children.Add(new MyClass { Property1 = "child1" });
var c2 = new MyClass { Property1 = "child2" };
c2.Children.Add(new MyClass { Property1 = "child21" });
test.Children.Add(c2);
test.Serialize("test.xml");
在生成的XML中,Children节点不应为空。
答案 0 :(得分:0)
添加
[XmlArray("Children"), XmlArrayItem("MyClass")]
public List<MyClass> Children { get; set; }
诀窍,对不起重复的问题