在阅读XML文档时如何使用XComment?

我正在使用以下行读取XML文档,该文档可能会或可能不会在我的XML文件顶部附近的“ ”括起来的一些注释:

 XDocument xe1 = XDocument.Load(filepath) 

我如何阅读评论并存储为字符串?

我在MS Visual Studio C#中这样做。

我知道有一些叫做“XComment”的东西,但我找不到一个在XML中读取时使用它的简单例子(我只能找到创建新XML文件的例子)。

-Adeena

使用此代码段获取XDocument中的所有注释:

 var document = XDocument.Load("test.xml"); var comments = from node in document.Elements().DescendantNodesAndSelf() where node.NodeType == XmlNodeType.Comment select node as XComment; 

这只解析顶级评论:

 var document = XDocument.Load("test.xml"); var comments = from node in document.Nodes() where node.NodeType == XmlNodeType.Comment select node as XComment;