命名数组中的每个元素

时间:2012-03-05 22:08:01

标签: c# xml serialization xml-serialization

我有一个数组,其索引映射回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>

我不能单独存储每个数字 - 它必须是一个数组。

感谢。

1 个答案:

答案 0 :(得分:4)

您可以使用XmlSerializer实现IXmlSerializable接口以完全自定义序列化。类似于以下内容:

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