c# - 使用 LINQ 解析 XML 获取子元素

标签 c# xml linq xml-parsing

<?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 语句来过滤数据(例如,仅从西部获取员工等...)

我一直在寻找一种更灵活的方式,使用 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>();

但我不确定如何从子节点获取值并应用过滤(仅获取某些员工)。这可能吗?感谢您的帮助。

谢谢

最佳答案

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

关于c# - 使用 LINQ 解析 XML 获取子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18891206/

相关文章:

c# - 在 LINQ 查询中只选择几列

.net - 如何在 linq to sql 中进行连接?

c# - 加快 datagridview 单元格字体更改

c# - 比较两个 XML 文件并在 C# 中使用 XMLDiff 生成第三个文件

.net - 将结果值转换为 Linq 中的字符串列表

python - 如何强制 ElementTree 将 xmlns 属性保留在其原始元素中?

java - 最佳实践 : Java/XML serialization: how to determine to what class to deserialize?

c# - 使用智能在 c# 中取缔字符串

c# - 按钮 onClick 未绑定(bind)到 Activity 中的方法

c# - 有没有一种技术可以区分泛型类型的类行为?