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

如何用LINQ和XDocument获取含指定关键词的XML属性值?

解决LINQ to XML提取含特定关键词的属性值问题

别担心,我来一步步帮你搞定这个需求!你要做的就是遍历XML里的所有属性,筛选出名称包含指定关键词的,再提取它们的值——用LINQ to XML其实很容易实现,我给你拆解清楚:

首先先回顾下你的XML结构:

核心思路

我们需要完成三个关键步骤:

  1. 遍历XML中所有层级的元素
  2. 取出每个元素的所有属性
  3. 筛选出属性名包含目标关键词(比如"id-ext")的项,提取它们的值

完整代码实现

下面是可直接运行的C#代码,我会逐行解释:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

public class XmlAttributeExtractor
{
    // 封装成通用方法:传入XDocument和关键词,返回匹配的属性值列表
    public static List<string> GetAttributeValuesByKeyword(XDocument xmlDoc, string keyword)
    {
        return xmlDoc.Descendants()
                     // 把每个元素的属性集合扁平化成一个全局属性序列
                     .SelectMany(element => element.Attributes())
                     // 筛选属性名包含关键词的项(用LocalName避免命名空间干扰)
                     .Where(attribute => attribute.Name.LocalName.Contains(keyword))
                     // 提取属性的值
                     .Select(attribute => attribute.Value)
                     // 转成List<string>返回
                     .ToList();
    }

    // 测试示例
    public static void Main()
    {
        // 从字符串加载XML(如果是文件的话,用XDocument.Load("你的文件路径")即可)
        string xmlContent = @"<document> 
                              <attribut1/> 
                              <attribut2> 
                                  <house price=""100"" location=""UK"" id-ext=""Id-100""/> 
                                  <house price=""300"" location=""GB"" id-int=""Id-101""/> 
                              </attribut2> 
                              <attribut3/> 
                          </document>";

        XDocument doc = XDocument.Parse(xmlContent);
        List<string> matchingValues = GetAttributeValuesByKeyword(doc, "id-ext");

        // 输出结果:Id-100
        foreach (string value in matchingValues)
        {
            Console.WriteLine(value);
        }
    }
}

关键代码说明

  • Descendants():这个方法会获取XML里所有嵌套层级的元素,不管它在<document>下还是<attribut2>下,都能被遍历到
  • SelectMany(...):如果只用Select,你得到的是每个元素对应的属性列表;而SelectMany会把这些列表合并成一个单一的属性序列,方便后续统一筛选
  • attribute.Name.LocalName:如果你的XML带有命名空间,LocalName会返回不带命名空间前缀的纯属性名;如果没有命名空间,直接用attribute.Name.ToString()也可以,但LocalName更通用
  • Contains(keyword):简单直接的字符串包含判断,满足你“属性名含特定字符”的需求
  • Select(attribute => attribute.Value):最后一步提取属性的实际值,转成列表返回

额外提示

如果你的XML是从文件读取的,只需要把XDocument.Parse(xmlContent)换成XDocument.Load("你的XML文件路径")就行;如果没有匹配到任何属性,方法会返回一个空列表,不会报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 21:43:13