You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C#和LINQ从XML中获取含父节点(部门)信息的员工数据?

问题解决

原始XML数据

<Department Name="Electronic">
  <Employee ID="1" Name="John" Address="xyz,abc" />
  <Employee ID="2" Name="Jim" Address="ntg,abc"/>
  <Employee ID="3" Name="Liz" Address="rhx,abc" />
</Department>
<Department Name="Computer">
  <Employee ID="1" Name="Tony" Address="mnc,abc"" />
  <Employee ID="2" Name="Tom" Address="abr,abc" />
</Department>

期望输出格式

Electronic, 1 , John
Electronic, 2 , Jim
Electronic, 3 , Liz
Computer,1,Tony
Computer,2,Tom

现有代码问题

你当前的LINQ查询仅提取了员工的ID和姓名,未关联父节点Department的名称:

var result1 = str.Elements("Department").Elements("Employee")
    .Select(node => new
    {
        ID = node.Attribute("ID").Value,
        Name = node.Attribute("Name").Value,
    }
    ).ToList();

修改后的代码

每个Employee节点的父节点就是对应的Department,直接通过node.Parent访问父节点,再获取其Name属性即可拿到部门名称。以下是两种实现方式:

方式1:返回包含部门信息的匿名对象

var result = str.Elements("Department")
               .Elements("Employee")
               .Select(node => new
               {
                   DepartmentName = node.Parent.Attribute("Name").Value,
                   ID = node.Attribute("ID").Value,
                   EmployeeName = node.Attribute("Name").Value
               })
               .ToList();

方式2:直接生成目标格式的字符串

如果不需要保留对象结构,可直接拼接出期望的文本行:

var outputLines = str.Elements("Department")
                     .Elements("Employee")
                     .Select(node => $"{node.Parent.Attribute("Name").Value},{node.Attribute("ID").Value},{node.Attribute("Name").Value}")
                     .ToList();

// 打印结果
foreach (var line in outputLines)
{
    Console.WriteLine(line);
}

执行后就能得到包含部门名称的目标输出。

内容的提问来源于stack exchange,提问作者usr021986

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 20:20:21