如何一次读取多个节点
本文关键字:节点 读取 何一次 | 更新日期: 2023-09-27 18:12:57
我有一个类:
class Employee
{
public int? ID { get; set; }
public int? EmployeeID { get; set; }
public string EmployeeName { get; set; }
public int? ChiefID { get; set; }
public string ChiefName { get; set; }
public List<int> ListOfEmployees { get; set; }
}
和xml是:
<?xml version="1.0" encoding="UTF8"?>
<Employee>
<Id>1</Id>
<EmloyeeId>1</EmployeeId>
<EmIoyeeName>Bob</EmIoyeeName>
<ChiefID></ChiefID>
<ChiefName></ChiefName>
<Dependent>
<idDependent>2</idDependent>
<idDependent>3</idDependent>
<idDependent>4</idDependent>
<idDependent>5</idDependent>
</Dependent>
</Employee>
</Employees>
我的c#代码是:
XDocument xDoc=LoadXML();
IEnumerable<Employee> sourceEmployee=xDoc.Descendants("Employee").Select(d=>new Employee {
ID=(int?)d.Element("Id"),
EmployeeID=(int?)d.Element("EmloyeeId"),
ListOfEmloyees=(List<int>)d.Element("Dependent").Elements("idDependent")//cannot populate ListOfEmloyees
});
然而,我无法读取数据到listofemployees属性。是否有可能读取"依赖"节点的后代的所有值?
将XElement
转换为int
,然后调用.ToList()
:
ListOfEmloyees = d.Elements("Dependent")
.Elements("idDependent")
.Select(o => (int)o)
.ToList()
我使用这个XML。它存储在c:'data文件夹
<?xml version="1.0" encoding="utf-8"?>
<Employees>
<Employee>
<Id>1</Id>
<EmployeeId>1</EmployeeId>
<EmployeeName>Bob</EmployeeName>
<ChiefID></ChiefID>
<ChiefName></ChiefName>
<Dependent>
<idDependent>2</idDependent>
<idDependent>3</idDependent>
<idDependent>4</idDependent>
<idDependent>5</idDependent>
</Dependent>
</Employee>
</Employees>
使用下面给出的代码
XDocument doc = XDocument.Load("c:''data''Employees.xml");
var employees = doc.Descendants("Employee");
foreach (var employee in employees)
{
Employee emp = new Employee();
emp.ID = Convert.ToInt32(employee.Element("Id").Value);
emp.EmployeeID = Convert.ToInt32(employee.Element("EmployeeId").Value);
emp.EmployeeName = employee.Element("EmployeeName").Value;
int ChiefIdValue;
int.TryParse(employee.Element("ChiefID").Value, out ChiefIdValue);
emp.ChiefID = ChiefIdValue;
emp.ChiefName = employee.Element("ChiefName").Value;
emp.ListOfEmployees = employee.Element("Dependent").Descendants("idDependent").Select(x => Convert.ToInt32(x.Value)).ToList<int>();
}