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

使用Linq to XML在C#中筛选数据失败,需获取Klaus值

排查Linq to XML读取自定义字段的问题

我来帮你梳理下代码里的几个关键问题,这应该就是你拿不到"Klaus"值的核心原因:

1. XML标签拼写错误(致命问题)

先看你给出的XML结构,自定义字段的容器标签写的是<cusomfields>——少了一个字母t,但你的C#代码里用的是c.Descendants("customfields")去查找节点,这直接导致代码找不到对应元素,自然读不到后续的值。

2. Linq查询逻辑方向有误

你当前的FirstName查询是先遍历customfields节点,再去检查它的子元素customfield的ID,但更合理的方式是直接遍历所有customfield节点,筛选出ID为customfield_37723的目标节点,逻辑更直接也不容易出错。

3. 取值路径错误

就算找到了目标customfield,你当前代码是取customfieldvalues的Value,但实际上customfieldvalues是容器节点,真正的字段值在它的子元素customfieldvalue里。


修正后的代码

XDocument doc = XDocument.Load(fileName);
var obj = (from c in doc.Descendants("item")
           select new ServiceRequest_NewUser()
           {
               TicketID = c.Element("key")?.Value ?? string.Empty,
               Summary = c.Element("summary")?.Value ?? string.Empty,
               ReporterNT = c.Element("reporter")?.Attribute("username")?.Value ?? string.Empty,
               ReporterFull = c.Element("reporter")?.Value ?? string.Empty,
               FirstName = (from f in c.Descendants("customfield")
                            where f.Attribute("id")?.Value == "customfield_37723"
                            select f.Descendants("customfieldvalue").FirstOrDefault()?.Value)
                           .FirstOrDefault() ?? string.Empty
           }).ToList();

foreach (var i in obj)
{
    Console.WriteLine($"{i.TicketID} {i.Summary} {i.ReporterNT} {i.ReporterFull} {i.FirstName}");
}

额外优化:空值保护

我在代码里加了?? string.Empty的空值判断,避免某个节点/属性不存在时抛出NullReferenceException,让代码更健壮。

另外,务必先把XML里的<cusomfields>改成<customfields>,保证标签拼写和代码一致!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 16:07:30