c# - 使用 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>
解决方案
您将 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);
}
推荐阅读
- r - 在 r 中创建一个稀疏矩阵,每行具有一组整数值
- javascript - 未运行 Jest+Enzyme API 模拟调用测试
- ocaml - 列表其余部分的模式匹配
- kotlin - 显示或隐藏小数
- php - 如何在两个php脚本之间切换
- google-apps-script - 如何在脚本中引用 Google 表格上的特定单元格?(最好在我离线时)
- python-3.x - 使用 args parser subparser set defaults 和导入函数的正确方法?
- opencl - 在 AMD GPU 上启动内核时查找计算单元 ID
- javascript - 在显示接收到的数据之前等待节点中的函数完成
- php - 带有单个 Laravel 安装的多个域