C# 如何查找具有特定属性值的xml节点

来源:这里教程网 时间:2026-02-21 17:29:03 作者:

在C#中查找具有特定属性值的XML节点,可以使用 System.Xml 命名空间中的 XDocumentXmlDocument 类。推荐使用 XDocument(LINQ to XML),语法更简洁直观。

使用 XDocument 和 LINQ 查找节点

假设你有如下XML内容:

<Root>
  <Person id="1" name="Alice" />
  <Person id="2" name="Bob" />
  <Person id="3" name="Alice" />
</Root>

你想查找 name 属性等于 "Alice" 的所有 Person 节点。

示例代码:

using System;
using System.Linq;
using System.Xml.Linq;
// 加载XML
XDocument doc = XDocument.Parse(xmlString); // 或 XDocument.Load("file.xml")
// 查找 name 属性为 "Alice" 的 Person 节点
var nodes = doc.Descendants("Person")
               .Where(e => e.Attribute("name")?.Value == "Alice");
foreach (var node in nodes)
{
    Console.WriteLine($"Found: {node.Attribute("id")?.Value}");
}

关键说明

Descendants("Person"):获取所有名为 Person 的后代节点。 e.Attribute("name")?.Value:安全获取属性值,避免空引用异常。 支持复杂条件,比如同时匹配多个属性:
.Where(e => e.Attribute("name")?.Value == "Alice" &&
             e.Attribute("id")?.Value == "1")

使用 XPath(可选)

如果你熟悉 XPath,也可以用 XPathSelectElements

var nodes = doc.XPathSelectElements("//Person[@name='Alice']");

需要引入命名空间:System.Xml.XPath,并通过 NuGet 安装 System.Xml.XPath.XDocument 包。

处理属性不存在的情况

如果某些节点可能没有目标属性,建议判断属性是否存在:

.Where(e => {
    var attr = e.Attribute("name");
    return attr != null && attr.Value == "Alice";
})
基本上就这些方法,使用 LINQ to XML 是最清晰、灵活的方式。

相关推荐