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

LINQ读取扁平化XML时部分字段返回Null问题求助

问题排查与修复

你的问题出在混淆了XML的**属性(Attribute)和子元素(Element)**的读取方式,同时节点层级引用错误,具体修复点如下:

错误分析

  • buildMach:你从BuildVerification节点(变量a)读取machine元素,但machine是<build>节点的属性,属于变量b(build节点)
  • p1、startTimeHeader、endTimeHeader、failureColumns:这些都是<Process>节点的属性,不是子元素,你用了Element()方法读取,自然返回Null

修复后的代码

string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string newPath = Path.GetFullPath(Path.Combine(path, @"..\.."));
string finalPathXmlb = Path.GetFullPath(Path.Combine(newPath, configFileName));
XDocument xmlDoc2 = XDocument.Load(finalPathXmlb);

var results1 = xmlDoc2.Descendants("BuildVerification")
    .SelectMany(a => a.Descendants("build")
        .SelectMany(b => b.Descendants("Process")
            .Select(p => new ProcessValidationInfo
            {
                // 直接从BuildVerification节点取codeFreezeTime子元素,无需通过b.Parent
                codeFreezeTime = a.Element("codeFreezeTime")?.Value,
                // 从build节点读取machine属性
                buildMach = b.Attribute("machine")?.Value,
                // 从Process节点读取name属性
                p1 = p.Attribute("name")?.Value,
                startTimeHeader = p.Attribute("startTimeHeader")?.Value,
                endTimeHeader = p.Attribute("endTimeHeader")?.Value,
                failureColumns = p.Attribute("failureColumns")?.Value,
                conditionList = p.Descendants("Condition")
                    .Select(c => new Condition
                    {
                        cName = c.Attribute("name")?.Value,
                        cValue = c.Attribute("value")?.Value,
                        cValueAlternate = c.Attribute("alternateValue")?.Value
                    })
                    .ToList(),
                successCriteriaList = p.Descendants("SuccessCriteria")
                    .Select(sc => new SuccessCriteria
                    {
                        f1 = sc.Element("field")?.Value,
                        c1 = sc.Element("comparison")?.Value,
                        v1 = sc.Element("value")?.Value,
                        alt_v1 = sc.Element("alternateValue")?.Value
                    })
                    .ToList()
            }))).ToList();

关键修改说明

  1. codeFreezeTime:简化读取逻辑,直接从BuildVerification节点(a)获取子元素,避免多余的层级跳转
  2. buildMach:将a.Element("machine")改为b.Attribute("machine"),对应<build machine="mach-31">的属性
  3. Process相关属性:所有p.Element(xxx)改为p.Attribute(xxx),对应<Process name="log1" startTimeHeader="StartTime"...>的属性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 19:10:15