2012-03-05 180 views
2

我有一個數組,其索引映射回Enum值。我想使用C#Xml序列化庫來序列化這個數組。但是,我希望每個Xml節點都能說出它所代表的Enum類型的名稱。我怎樣才能做到這一點?命名數組中的每個元素

例子:

public class NumberOfEmployees 
{ 
    public enum EmployeeType { Lawyer, Doctor, Engineer }; 

    public int[] NumEmployees { get; set; } 

    // Constructor initializes array to size of "EmployeeType" 
    public NumberOfEmployees() 
    { 
     int size = Enum.GetValues(typeof(EmployeeType)).Length; 
     this.NumEmployees = new int[size]; 
    }  
} 


Main() 
{ 
    NumberOfEmployees numEmployees = new NumberOfEmployees(); 
    // Add doctors, lawyers, engineers, etc... 
    // numEmployees.NumEmployees[(int)NumberOfEmployees.Lawyer] = 3; 
    // numEmployees.NumEmployees[(int)NumberOfEmployees.Doctor] = 2; 
    // numEmployees.NumEmployees[(int)NumberOfEmployees.Engineer] = 1; 

    // Serialize to "file" 
    FileStream fs = new FileStream(file, FileMode.OpenOrCreate); 
    XmlSerializer xml = new XmlSerializer(typeof(NumberOfEmployees)); 
    xml.Serialize(fs, numEmployees); 
    fs.Close(); 
} 

最終的結果是XML,看起來是這樣的:

<NumEmployees> 
    <int>3</int> 
    <int>2</int> 
    <int>1</int> 
</NumEmployees> 

但我想要的是:

<NumEmployees> 
    <Lawyer>3</Lawyer> 
    <Doctor>2</Doctor> 
    <Engineer>1</Engineer> 
</NumEmployees> 

我不能存儲的每個號碼分開 - 它必須是一個數組。

謝謝。

回答

4

您可以實現IXmlSerializable接口以使用XmlSerializer完全自定義序列化。一些類似以下內容:

public class NumberOfEmployees : IXmlSerializable 
{ 
    public int[] NumEmployees { get; set; } 

    // Constructor initializes array to size of "EmployeeType" 
    public NumberOfEmployees() 
    { 
     int size = Enum.GetValues(typeof(EmployeeType)).Length; 
     this.NumEmployees = new int[size]; 
    } 

    public XmlSchema GetSchema() 
    { 
     return null; 
    } 

    public void ReadXml(XmlReader reader) 
    { 
     reader.ReadStartElement(); 
     NumEmployees[(int)EmployeeType.Lawyer] = int.Parse(reader.ReadElementString("Lawyer")); 
     NumEmployees[(int)EmployeeType.Doctor] = int.Parse(reader.ReadElementString("Doctor")); 
     NumEmployees[(int)EmployeeType.Engineer] = int.Parse(reader.ReadElementString("Engineer")); 
     reader.ReadEndElement(); 
    } 

    public void WriteXml(XmlWriter writer) 
    { 
     writer.WriteElementString("Lawyer", NumEmployees[(int)EmployeeType.Lawyer].ToString()); 
     writer.WriteElementString("Doctor", NumEmployees[(int)EmployeeType.Doctor].ToString()); 
     writer.WriteElementString("Engineer", NumEmployees[(int)EmployeeType.Engineer].ToString()); 
    } 
} 

後,你已經做了所有這也許顯得毫無意義仍然使用XmlSerializer,因爲你的類序列化處理的全部工作。但是,如果NumberOfEmployees是更大的XML結構的一部分(我認爲它是這樣),它仍然是有意義的。

另請注意,代碼不會進行任何驗證,因爲這是一個簡單的示例。因此,當類被序列化時,所有三個數組元素都應該存在,並且所有三個XML元素在反序列化時都會存在。在IXmlSerializable接口

更多信息,請訪問:

http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx

相關問題