Public Class Employee
{
Public String EmployeeId {get;set;}
Public String EmployeeName {get;set;}
Public String Department {get;set;}
}
Public Class Department
{
Public String DepartmentId {get;set;}
Public String DepartmentName {get;set;}
Public String Address {get;set;}
}
Public Class Address
{
Public String AddrOne {get;set;}
Public String City {get;set;}
}
我有3个模型,列表,列表和列表 执行程序后,上面提到的3个模型应该填充List,List和List 我必须以下面的格式返回数据......
以下格式获得回复的最佳方法是什么?
<Employees>
<Employee>
<EmployeeID> </EmployeeID>
<EmployeeName> </EmployeeName>
<Department>
<DepartmentID> </DepartmentID>
<DepartmentName> </DepartmentName>
<Address>
<Addr1> </Addr1>
<City> </City>
</Address>
<Department>
</Employee>
</Employees>
答案 0 :(得分:1)
您可以创建以下类:
public class Model
{
public List<Employee> Employees { get; set; }
}
public class Employee
{
public string EmployeeId { get; set; }
public string EmployeeName { get; set; }
public Department Department { get; set; }
}
public class Department
{
public string DepartmentId { get; set; }
public string DepartmentName {get; set; }
public Address Address { get; set; }
}
public class Address
{
public string AddrOne { get; set; }
public string City { get; set; }
}
接下来,您可以创建模型的实例并填充数据并将其序列化为XML
答案 1 :(得分:0)
XML序列化:
创建一个CollectionClass并添加方法来序列化它:
public class MyCollection
{
public List<Employee> = new List<Employee>();
public List<Department> = new List<Department>();
public List<Address> = new List<Address>();
public string ToXML()
{
var stringwriter = new System.IO.StringWriter();
var serializer = new XmlSerializer(this.GetType());
serializer.Serialize(stringwriter, this);
return stringwriter.ToString();
}
// You have to use your Class-Type here 3 times
public static MyCollection LoadFromXML(string filePath)
{
using (StreamReader streamReader = new System.IO.StreamReader(filePath))
{
var serializer = new XmlSerializer(typeof(MyCollection));
return serializer.Deserialize(streamReader) as MyCollection;
}
}
}
现在您可以将您的类保存为xml-File:
MyCollection myCollection = new MyCollection();
//Now add your entries, myCollection.Add(new Department(....));
//Save your class as xml-File
File.WriteAllText("C:\\MyClass.xml", myCollection.ToXML());
然后你可以加载它:
//Load your class
MyCollection myCollection = MyCollection.LoadFromXML("C:\\MyClass.xml");
编辑:将其更改为CollectionClass-Sample,它应该适合您的情况