如何将A类和B类的两个对象序列化为xml,以便它可以采用以下格式:
<root>
<objClassA> //Parent Node
<objClassB> // child node of objClassA
</objClassB>
</objClassA>
</root>
答案 0 :(得分:1)
[Serializable(true)]
public class objClassB
{
}
[Serializable(true)]
public class objClassA
{
public objClassB instance;
}
然后使用XmlSerializer作为objClassA的一个实例,它将自动将b的实例作为子项放在其自身内。
答案 1 :(得分:1)
using System; using System.IO; using System.Xml.Serialization; void Write(root rootInstance) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(root)); using (FileStream fileStream = new FileStream("filepath.xml", FileMode.Create)) { xmlSerializer.Serialize(fileStream, rootInstance); } } public class root { public ClassA objClassA { get; set; } } public class ClassA { public ClassB objClassB { get; set; } } public class ClassB { }