使用XmlDocument或XDocument可获取XML属性值:先加载XML,再通过XPath或LINQ定位节点,最后读取Attribute.Value;含命名空间时需声明XNamespace。

在C#中获取XML特定属性的值,可以通过多种方式实现,常用的方法包括使用 XmlDocument、XDocument(LINQ to XML)以及 XmlNodeReader。下面介绍几种实用且清晰的查询方法。
XmlDocument 适合处理结构较复杂的XML文件,通过XPath定位节点并读取属性。
示例XML:<Books> <Book id="1" title="C#入门" author="张三" /> <Book id="2" title="XML编程" author="李四" /> </Books>
获取第一个 Book 节点的 title 属性值:
XmlDocument doc = new XmlDocument();
doc.Load("books.xml"); // 或 LoadXml("字符串")
XmlNode node = doc.SelectSingleNode("/Books/Book");
if (node != null && node.Attributes["title"] != null)
{
    string title = node.Attributes["title"].Value;
    Console.WriteLine(title); // 输出:C#入门
}
查找 id="2" 的 Book 的 author 属性:
XmlNode node = doc.SelectSingleNode("/Books/Book[@id='2']");
if (node != null)
{
    string author = node.Attributes["author"].Value;
    Console.WriteLine(author); // 输出:李四
}
XDocument 更现代,语法更简洁,推荐用于新项目。
XDocument xDoc = XDocument.Load("books.xml");
var book = xDoc.Descendants("Book")
               .FirstOrDefault(b => b.Attribute("id")?.Value == "2");
if (book != null)
{
    string title = book.Attribute("title")?.Value;
    Console.WriteLine(title); // 输出:XML编程
}
也可以直接遍历所有 Book 节点并提取属性:
var books = xDoc.Descendants("Book");
foreach (var b in books)
{
    string id = b.Attribute("id")?.Value;
    string title = b.Attribute("title")?.Value;
    Console.WriteLine($"ID: {id}, Title: {title}");
}
如果XML包含命名空间,必须在查询时指定。
示例带命名空间的XML:<?xml version="1.0" encoding="utf-8"?> <Books xmlns="http://example.com/ns"> <Book id="1" title="Web开发" /> </Books>
正确读取方式:
XNamespace ns = "http://example.com/ns";
XDocument xDoc = XDocument.Load("books.xml");
var book = xDoc.Descendants(ns + "Book").FirstOrDefault();
if (book != null)
{
    string title = book.Attribute("title")?.Value;
    Console.WriteLine(title); // 输出:Web开发
}
选择哪种方式取决于你的场景:
基本上就这些,掌握 SelectSingleNode 和 Descendants 配合属性查询,就能应对大多数需求。
以上就是C#怎么获取XML特定属性的值_C#查询XML节点特定属性值方法的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号