我想你需要使用XmlType
屬性來確保您的元素顯示爲<HR>
和<IT>
而不是<employee xsi:type="HR">
。下面的工作演示:
public abstract class Employee
{
public string Name { get; set; }
public string ID { get; set; }
public Employee(string Name, string ID)
{
this.Name = Name;
this.ID = ID;
}
}
public class HR : Employee
{
public HR(string Name, string ID) : base(Name, ID)
{
}
public HR() : base("No name", "No ID")
{
}
}
public class IT : Employee
{
public IT(string Name, string ID) : base(Name, ID)
{
}
public IT() : base("No name", "No ID")
{
}
}
我添加了序列化程序的默認(無參數)構造函數。
然後,你必須有某種包裝對象來處理的Employee
個清單:
public class Employees
{
[XmlElement(typeof(IT))]
[XmlElement(typeof(HR))]
public List<Employee> Employee { get; set; } //It doesn't really matter what this field is named, it takes the class name in the serialization
}
接下來,您可以使用串行代碼從我的評論生成XML:
var employees = new Employees
{
Employee = new List<Employee>()
{
new IT("Sugan", "88"),
new HR("Niels", "41")
}
};
var serializer = new XmlSerializer(typeof(Employees));
var xml = "";
using (var sw = new StringWriter())
{
using (XmlWriter writer = XmlWriter.Create(sw))
{
serializer.Serialize(writer, employees);
xml = sw.ToString();
}
}
Console.WriteLine(xml);
(ommitted爲清楚起見命名空間)
這將返回以下XML:
<?xml version="1.0" encoding="UTF-8"?>
<Employees xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<IT>
<Name>Sugan</Name>
<ID>88</ID>
</IT>
<HR>
<Name>Niels</Name>
<ID>41</ID>
</HR>
</Employees>
您的課程還存在其他一些錯誤。你在'Employee'基類中定義'ID'是一個'string',但在'HR'類和'IT'類中,你傳遞一個'int'作爲ID。另外,爲了調用基類,你應該使用'base(Name,ID)'而不是'Employee(Name,ID)'。 – nbokmans
@nbokmans道歉。這只是一個錯字。我現在編輯並更新了代碼。感謝您指出。 – Sugan88
對於Xml Serializer來說,您的類必須具有公共的無參數構造函數。 –