我希望能够在使用Roslyn解析C#源代码时阅读XML文档注释。
/// <summary>
/// Documentation...
/// </summary>
我尝试在ParseOptions中设置ParseDocumentationComments,但它似乎没有效果?
var parseOptions = ParseOptions.Default.WithParseDocumentationComments(true);
SyntaxTree unit = SyntaxTree.ParseFile(file, parseOptions);
答案 0 :(得分:29)
您需要:
LeadingTrivia
Compilation
,找到包含XML文档注释的Symbol
并在其上使用GetDocumentationComment()
方法。一个完整的例子:
using Roslyn.Compilers.CSharp;
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var tree = SyntaxTree.ParseText(@"
/// <summary>This is an xml doc comment</summary>
class C
{
}");
var classNode = (ClassDeclarationSyntax)tree.GetRoot().Members.First();
var trivia = classNode.GetLeadingTrivia().Single(t => t.Kind == SyntaxKind.DocumentationCommentTrivia);
var xml = trivia.GetStructure();
Console.WriteLine(xml);
var compilation = Compilation.Create("test", syntaxTrees: new[] { tree });
var classSymbol = compilation.GlobalNamespace.GetTypeMembers("C").Single();
var docComment = classSymbol.GetDocumentationComment();
Console.WriteLine(docComment.SummaryTextOpt);
}
}
答案 1 :(得分:6)
通过nuget
代码如下:
using System;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
class Program
{
static void Main(string[] args)
{
var tree = CSharpSyntaxTree.ParseText(@"
/// <summary> This is an xml doc comment </summary>
class C
{
}");
var root = (CompilationUnitSyntax) tree.GetRoot();
var classNode = (ClassDeclarationSyntax) (root.Members.First());
var trivias = classNode.GetLeadingTrivia();
var xmlCommentTrivia = trivias.FirstOrDefault(t => t.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia);
var xml = xmlCommentTrivia.GetStructure();
Console.WriteLine(xml);
var compilation = CSharpCompilation.Create("test", syntaxTrees: new[] {tree});
var classSymbol = compilation.GlobalNamespace.GetTypeMembers("C").Single();
var docComment = classSymbol.GetDocumentationCommentXml();
Console.WriteLine(docComment);
}
}
答案 2 :(得分:2)
更新:
FirstOrDefault
方法不再可用。所以请改用enumerator
。
更新代码:
using System;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
class Program
{
static void Main(string[] args)
{
var tree = CSharpSyntaxTree.ParseText(@"
/// <summary> This is an xml doc comment </summary>
class C
{
}");
var root = (CompilationUnitSyntax) tree.GetRoot();
var classNode = (ClassDeclarationSyntax) (root.Members.First());
var trivias = classNode.GetLeadingTrivia();
var enumerator = trivias.GetEnumerator();
while (enumerator.MoveNext())
{
var trivia = enumerator.Current;
if(trivia.Kind().Equals(SyntaxKind.SingleLineDocumentationCommentTrivia))
{
var xml = trivia.GetStructure();
Console.WriteLine(xml);
}
}
}
}