使用XDocument和LINQ可高效查找特定属性值的XML节点,如通过Descendants和Where方法筛选name为Alice的Person节点,并用Attribute?.Value安全获取属性值。

在C#中查找具有特定属性值的XML节点,可以使用 System.Xml 命名空间中的 XDocument 或 XmlDocument 类。推荐使用 XDocument(LINQ to XML),语法更简洁直观。
假设你有如下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}");
}
.Where(e => e.Attribute("name")?.Value == "Alice" &&
             e.Attribute("id")?.Value == "1")
如果你熟悉 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";
})
以上就是C# 如何查找具有特定属性值的xml节点的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号