答案:C#中获取XML节点属性值常用XmlDocument和XDocument。1. XmlDocument通过SelectSingleNode定位节点,用Attributes[“属性名”]获取值,适用于旧项目;2. XDocument使用Attribute(“属性名”)?.Value语法更简洁,推荐现代项目使用;3. 建议用?.操作符避免空引用异常,属性存在时取值,不存在返回null;4. 可从文件加载或字符串解析XML,根据需求选择合适方法。

在 C# 中获取 XML 节点的属性值,常用的方法是使用 XmlDocument 或 XDocument(LINQ to XML)。下面介绍两种方式的具体用法。
使用 XmlDocument 获取属性值
适用于较老的 .NET Framework 项目,操作方式类似 DOM。
步骤如下:
加载 XML 文档通过 SelectSingleNode 或 GetElementsByTagName 定位节点使用 Attributes 属性获取指定属性的值
示例代码:
using System;using System.Xml;XmlDocument doc = new XmlDocument();doc.Load("test.xml"); // 或 LoadXml("C# Guide");
XmlNode node = doc.SelectSingleNode("/book");if (node != null && node.Attributes["id"] != null){string id = node.Attributes["id"].Value;string price = node.Attributes["price"]?.Value; // 可空属性建议用 ?Console.WriteLine($"ID: {id}, Price: {price}");}
使用 XDocument (LINQ to XML) 获取属性值
推荐用于现代 C# 项目,语法更简洁,支持 LINQ 查询。
使用 XElement.Attribute(“属性名”).Value 或更安全的 Attribute(“属性名”)?.Value
示例代码:
using System;using System.Xml.Linq;XDocument xDoc = XDocument.Load("test.xml"); // 或 Parse 字符串// 示例 XML: C# Guide
XElement book = xDoc.Root;string id = book.Attribute("id")?.Value;string price = book.Attribute("price")?.Value;
if (!string.IsNullOrEmpty(id)){Console.WriteLine($"ID: {id}, Price: {price}");}
注意事项
访问属性前务必判断属性是否存在,避免 NullReferenceException使用 ?. 操作符可以安全取值,属性不存在时返回 null如果属性是必需的,可使用 Attribute(“name”).Value,但要确保一定存在,否则抛异常支持从字符串解析 XML,也可直接读文件
基本上就这些,根据项目选择合适的方式。XDocument 更现代简洁,XmlDocument 兼容性好。
以上就是C# 怎么获取xml节点的属性值的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1440985.html
微信扫一扫
支付宝扫一扫