如何一次读取多个节点?

时间:2015-09-15 08:30:45

标签: c# xml wpf linq-to-xml .net-4.5

我有一个班级:

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
      });

但是,我无法将数据读取到ListOfEmployes属性。是否可以读取“从属”节点后代的所有值?

2 个答案:

答案 0 :(得分:2)

XElement转换为int,然后致电.ToList()

ListOfEmloyees = d.Elements("Dependent")
                  .Elements("idDependent")
                  .Select(o => (int)o)
                  .ToList()

答案 1 :(得分:0)

我使用这个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>();

        }