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

在 C# 中获取 XML 节点的属性值,常用的方法是使用 XmlDocument 或 XDocument(LINQ to XML)。下面介绍两种方式的具体用法。
步骤如下:
示例代码:
using System;
using System.Xml;
<p>XmlDocument doc = new XmlDocument();
doc.Load("test.xml"); // 或 LoadXml("<book id='101' price='25.5'>C# Guide</book>");</p><p>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}");
}
使用 XElement.Attribute("属性名").Value 或更安全的 Attribute("属性名")?.Value
示例代码:
using System;
using System.Xml.Linq;
<p>XDocument xDoc = XDocument.Load("test.xml"); // 或 Parse 字符串
// 示例 XML: <book id="101" price="25.5">C# Guide</book></p><p>XElement book = xDoc.Root;
string id = book.Attribute("id")?.Value;
string price = book.Attribute("price")?.Value;</p><p>if (!string.IsNullOrEmpty(id))
{
Console.WriteLine($"ID: {id}, Price: {price}");
}
基本上就这些,根据项目选择合适的方式。XDocument 更现代简洁,XmlDocument 兼容性好。
以上就是C# 怎么获取xml节点的属性值的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号