首页 > 解决方案 > 使用 ForEach 循环遍历反序列化的 XML 循环错误

问题描述

使用 foreach 循环遍历反序列化的 xml 时出现以下错误。

“Foreach 循环无法对‘Employeez’类型的变量进行操作,因为‘Employeez’不包含‘GetEnumerator’的公共实例或扩展定义

Program.cs 看起来像这样:

{
    class Program : ParentClass
    {
        static void Main(string[] args)
        {

            DeSerializeEmp();

        }


        static void DeSerializeEmp()
        {

            string filePath = @"C:\Users\nabee\OneDrive\Desktop\XMLTest\";
            string fileName = @"myXmlFile.xml";


            XmlSerializer getEmps = new XmlSerializer(typeof(Employeez));

            using (XmlReader myXmlReader = XmlReader.Create(filePath + fileName))
            {
                Employeez allEmps = (Employeez)getEmps.Deserialize(myXmlReader);

                
                
                foreach (Employee myEmps in allEmps)
                {
                    Console.WriteLine(myEmps.fullName);
                }
            }

            


        }
    }
}

我的数据结构类看起来像:

{

    [XmlRoot("Employeez")]
    public class Employeez
    {
        [XmlElement("Employee")]
        public List<Employee> Employee
        {
            get; set;
        }
    }


    
    [XmlRoot("Employee")]
    public class Employee
    {

        [XmlElement("EmpId")]
        public int empId {get; set;}

        [XmlElement("Name")]
        public string fullName { get; set; }

        /*[XmlElement("BirthDate")]
        public DateTime DOB { get; set; }*/
    }

}

XML看起来像

<?xml version="1.0" encoding="utf-8"?>
<Employeez>
  <Employee>
<EmpId>12065</EmpId>
  <Name>Nabeel John</Name>
  <BirthDate>2021-02-16T21:59:23.7505798-05:00</BirthDate>
</Employee>
  <Employee>
<EmpId>12208</EmpId>
  <Name>Richard John</Name>
  <BirthDate>1986-02-16T21:59:23.7505798-05:00</BirthDate>
</Employee>
</Employeez>

标签: c#xmldeserialization

解决方案


您将 xml 反序列化为类(好的做法是定义类型)

[XmlRoot("Employeez")]
public class Employeez
{
    [XmlElement("Employee", Type = typeof(Employee))]
    public List<Employee> Employee
    {
        get; set;
    }
}

所以当你想阅读员工时,你可以这样做:

foreach (Employee myEmps in allEmps.Employee)
{
   Console.WriteLine(myEmps.fullName);
}

推荐阅读