使用XmlDocument或XDocument可读取XML注释。XmlDocument通过SelectNodes("//comment()")获取所有注释节点,XDocument利用Descendants().SelectMany(e=>e.Nodes()).OfType<XComment>()筛选注释,二者均用Value属性提取内容。

在 C# 中读取 XML 文件中的注释内容,可以使用 XmlDocument 或 XDocument(LINQ to XML)来实现。XML 注释节点属于特殊类型的节点(XmlComment),需要通过遍历节点树并筛选出注释类型节点才能获取。
使用 XmlDocument 读取注释
XmlDocument 是传统的 XML 处理方式,适合处理较复杂的 XML 文档结构。
示例代码:
using System;
using System.Xml;
<p>class Program
{
static void Main()
{
XmlDocument doc = new XmlDocument();
doc.Load("example.xml"); // 替换为你的文件路径</p><pre class='brush:php;toolbar:false;'> // 获取所有注释节点
XmlNodeList commentNodes = doc.SelectNodes("//comment()");
foreach (XmlNode node in commentNodes)
{
Console.WriteLine("注释内容: " + node.Value);
}
}}
说明:
- SelectNodes("//comment()") 使用 XPath 语法查找文档中所有注释节点。
- node.Value 获取注释文本内容(不包含 <!-- 和 -->)。
使用 XDocument(LINQ to XML)读取注释
XDocument 更现代、简洁,推荐用于新项目。
using System;
using System.Linq;
using System.Xml.Linq;
<p>class Program
{
static void Main()
{
XDocument doc = XDocument.Load("example.xml");</p><pre class='brush:php;toolbar:false;'> var comments = doc.Descendants().SelectMany(e => e.Nodes())
.OfType<XComment>()
.Select(c => c.Value);
foreach (string comment in comments)
{
Console.WriteLine("注释内容: " + comment);
}
}}
说明:
- Descendants() 获取所有元素。
- SelectMany(e => e.Nodes()) 展开所有节点(包括注释)。
- OfType<XComment>() 筛选出注释类型节点。
- c.Value 获取注释文本。
注意事项
确保 XML 文件中确实包含注释,例如:
<root><!-- 这是一个配置说明 -->
<data name="test">value</data>
</root>
该注释会被正确读取为 "这是一个配置说明"。
基本上就这些方法,根据项目选择 XmlDocument 或 XDocument 均可,后者语法更简洁。注意注释节点不会被当作普通元素处理,必须显式提取。










