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

C# LINQ to XML:筛选属性以指定前缀开头的后代元素

解决方案

先贴符合场景的XML示例:

<Root>
  <Element Name="CFF Container.205">
    <Child>Sample Content A</Child>
  </Element>
  <Element Name="CFF Container.101">
    <Child>Sample Content B</Child>
  </Element>
  <Element Name="Unrelated.Item">
    <Child>Sample Content C</Child>
  </Element>
</Root>

原精确匹配代码(仅支持完全一致的Name)

// 只能匹配固定后缀的元素,灵活性差
var exactMatch = doc.Descendants("Element")
                    .FirstOrDefault(e => e.Attribute("Name").Value == "CFF Container.205")
                    ?.Parent;

修改为前缀匹配的正确写法(保留.Parent链式调用)

方式1:LINQ to XML(推荐)

// 筛选所有Name以"CFF Container"开头的元素,批量获取它们的Parent
var prefixMatchedParents = doc.Descendants("Element")
                              // 先判断Name属性存在,再检查前缀,避免空引用异常
                              .Where(e => e.Attribute("Name")?.Value.StartsWith("CFF Container") == true)
                              .Select(e => e.Parent);

// 如果只需要第一个匹配元素的Parent
var firstMatchedParent = doc.Descendants("Element")
                            .FirstOrDefault(e => e.Attribute("Name")?.Value.StartsWith("CFF Container") == true)
                            ?.Parent;

方式2:XPath语法

// 用XPath直接定位符合前缀条件的元素,再取Parent
var xpathMatchedParents = doc.XPathSelectElements("//Element[starts-with(@Name, 'CFF Container')]")
                             .Select(e => e.Parent);

报错原因及注意事项

  • 之前报错大概率是未处理Name属性为null的情况:直接调用e.Attribute("Name").Value会在元素没有Name属性时抛出空引用异常,必须用?.空条件运算符做安全访问。
  • 如果需要忽略大小写匹配,修改StartsWith参数:
    e.Attribute("Name")?.Value.StartsWith("CFF Container", StringComparison.OrdinalIgnoreCase) == true
    
  • 链式调用?.Parent可以避免在没有匹配元素时抛出异常,返回null而非报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 00:45:24