【发布时间】:2021-05-23 01:13:32
【问题描述】:
使用 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>
【问题讨论】:
-
应该是:foreach (Employee myEmps in allEmps.Employee)
标签: c# xml deserialization