6
<?xml version="1.0" standalone="yes"?>
<CompanyInfo>
     <Employee name="Jon" deptId="123">
      <Region name="West">
        <Area code="96" />
      </Region>
      <Region name="East">
        <Area code="88" />
      </Region>
     </Employee>
</CompanyInfo>  

public class Employee
{
    public string EmployeeName { get; set; }
    public string DeptId { get; set; }
    public List<string> RegionList {get; set;}
}

public class Region
{
    public string RegionName { get; set; }
    public string AreaCode { get; set; }
}

我正在尝试读取此 XML 数据,到目前为止,我已经尝试过:

XDocument xml = XDocument.Load(@"C:\data.xml");
var xElement = xml.Element("CompanyInfo");
if (xElement != null)
    foreach (var child in xElement.Elements())
    {
        Console.WriteLine(child.Name);  
        foreach (var item in child.Attributes())
        {
            Console.WriteLine(item.Name + ": " + item.Value);
        }

        foreach (var childElement in child.Elements())
        {
            Console.WriteLine("--->" + childElement.Name);
            foreach (var ds in childElement.Attributes())
            {
                Console.WriteLine(ds.Name + ": " + ds.Value);
            }
            foreach (var element in childElement.Elements())
            {
                Console.WriteLine("------->" + element.Name);
                foreach (var ds in element.Attributes())
                {
                    Console.WriteLine(ds.Name + ": " + ds.Value);
                }
            }
        }                
    }

这使我能够获取每个节点、它的属性名称和值,因此我可以将这些数据保存到数据库中的相关字段中,但这似乎是一种冗长的方式并且不灵活,例如,如果 XML 结构改变了所有这些 foreach 语句需要重新访问,也很难以这种方式过滤数据,我需要编写某些 if 语句来过滤数据(例如,仅从 West 获取员工等...)

我正在寻找一种更灵活的方式,使用 linq,如下所示:

List<Employees> employees =
              (from employee in xml.Descendants("CompanyInfo")
               select new employee
               {
                   EmployeeName = employee.Element("employee").Value,
                   EmployeeDeptId = ?? get data,
                   RegionName = ?? get data,
                   AreaCode = ?? get data,,
               }).ToList<Employee>();

但我不确定如何从子节点获取值并应用过滤(仅获取某些员工)。这可能吗?任何帮助表示赞赏。

谢谢

4

3 回答 3

8
var employees = (from e in xml.Root.Elements("Employee")
                 let r = e.Element("Region")
                 where (string)r.Attribute("name") == "West"
                 select new Employee
                 {
                     EmployeeName = (string)e.Attribute("employee"),
                     EmployeeDeptId = (string)e.Attribute("deptId"),
                     RegionName = (string)r.Attribute("name"),
                     AreaCode = (string)r.Element("Area").Attribute("code"),
                 }).ToList();

但当 XML 文件结构发生变化时,仍需要修改查询。

编辑

查询每个员工的多个区域:

var employees = (from e in xml.Root.Elements("Employee")
                 select new Employee
                 {
                     EmployeeName = (string)e.Attribute("employee"),
                     DeptId = (string)e.Attribute("deptId"),
                     RegionList = e.Elements("Region")
                                   .Select(r => new Region {
                                       RegionName = (string)r.Attribute("name"),
                                       AreaCode = (string)r.Element("Area").Attribute("code")
                                   }).ToList()
                 }).ToList();

然后,您可以仅过滤来自给定区域的员工列表:

var westEmployees = employees.Where(x => x.RegionList.Any(r => r.RegionName == "West")).ToList();
于 2013-09-19T09:46:59.183 回答
6

您可以跟踪结构:

from employee in xml
      .Element("CompanyInfo")       // must be root
      .Elements("Employee")         // only directly children of CompanyInfo

或不那么严格

from employee in xml.Descendants("Employee")    // all employees at any level

然后得到你想要的信息:

       select new Employee
       {
           EmployeeName = employee.Attribute("name").Value,
           EmployeeDeptId = employee.Attribute("deptId").Value,
           RegionName = employee.Element("Region").Attribute("name").Value,
           AreaCode = employee.Element("Region").Element("Area").Attribute("code").Value,
       }

并带有有关多个区域的附加信息,假设有一个List<Region> Regions属性:

       select new Employee
       {
           EmployeeName = employee.Attribute("name").Value,
           EmployeeDeptId = employee.Attribute("deptId").Value,
           //RegionName = employee.Element("Region").Attribute("name").Value,
           //AreaCode = employee.Element("Region").Element("Area").Attribute("code").Value,
           Regions = (from r in employee.Elements("Region") select new Region 
                      {
                         Name = r.Attribute("name").Value,
                         Code = r.Element("Area").Attribute("code").Value,
                      }).ToList();
       }
于 2013-09-19T09:46:47.393 回答
2

您可以在一个查询中进行选择,然后在第二个查询中进行过滤,或者将它们组合到一个查询中:

两个查询:

        // do te transformation
        var employees =
          from employee in xml.Descendants("CompanyInfo").Elements("Employee")
          select new
          {
              EmployeeName = employee.Attribute("name").Value,
              EmployeeDeptId = employee.Attribute("deptId").Value,
              Regions = from region in employee.Elements("Region")
                        select new
                            {
                                Name = region.Attribute("name").Value,
                                AreaCode = region.Element("Area").Attribute("code").Value,
                            }
          };

        // now do the filtering
        var filteredEmployees = from employee in employees
                                from region in employee.Regions
                                where region.AreaCode == "96"
                                select employee;

合并一个查询(相同的输出):

          var employees2 =
          from selectedEmployee2 in
              from employee in xml.Descendants("CompanyInfo").Elements("Employee")
              select new
              {
                  EmployeeName = employee.Attribute("name").Value,
                  EmployeeDeptId = employee.Attribute("deptId").Value,
                  Regions = from region in employee.Elements("Region")
                            select new
                                {
                                    Name = region.Attribute("name").Value,
                                    AreaCode = region.Element("Area").Attribute("code").Value,
                                }
              }
          from region in selectedEmployee2.Regions
          where region.AreaCode == "96"
          select selectedEmployee2;

但是您应该考虑添加一件小事。为了稳健性,您需要检查元素和属性是否存在,然后选择将如下所示:

 var employees =
          from employee in xml.Descendants("CompanyInfo").Elements("Employee")
          select new
          {
              EmployeeName = (employee.Attribute("name") != null) ? employee.Attribute("name").Value : string.Empty,
              EmployeeDeptId = (employee.Attribute("deptId") != null) ? employee.Attribute("deptId").Value : string.Empty,
              Regions = (employee.Elements("Region") != null)?
                        from region in employee.Elements("Region")
                        select new
                            {
                                Name = (region.Attribute("name")!= null) ? region.Attribute("name").Value : string.Empty,
                                AreaCode = (region.Element("Area") != null && region.Element("Area").Attribute("code") != null) ? region.Element("Area").Attribute("code").Value : string.Empty,
                            }
                        : null
          };
于 2013-09-19T10:50:33.197 回答