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

在C#中查找具有特定属性值的XML节点,可以使用 System.Xml 命名空间中的 XDocument 或 XmlDocument 类。推荐使用 XDocument(LINQ to XML),语法更简洁直观。
使用 XDocument 和 LINQ 查找节点
假设你有如下XML内容:
你想查找 name 属性等于 “Alice” 的所有 Person 节点。
示例代码:
using System;using System.Linq;using System.Xml.Linq;// 加载XMLXDocument 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 是最清晰、灵活的方式。
以上就是C# 如何查找具有特定属性值的xml节点的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1441003.html
微信扫一扫
支付宝扫一扫