如何使用Roslyn阅读XML文档注释 [英] How to read XML documentation comments using Roslyn

查看:55
本文介绍了如何使用Roslyn阅读XML文档注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用Roslyn解析C#源代码时,我希望能够阅读XML文档注释。

I would like to be able to read XML documentation comments while parsing C# source code using Roslyn.

/// <summary>
/// Documentation...
/// </summary>

我尝试在ParseOptions中设置ParseDocumentationComments,但这似乎没有效果吗?

I tried setting the ParseDocumentationComments in the ParseOptions, but it doesn't seem to have an effect?

var parseOptions = ParseOptions.Default.WithParseDocumentationComments(true);
SyntaxTree unit = SyntaxTree.ParseFile(file, parseOptions);


推荐答案

您需要:


  1. 查看包含XML文档注释的语法的 LeadingTrivia

  2. 构造一个编译,找到具有XML文档注释的符号并使用 GetDocumentationComment()方法。

  1. Look at the LeadingTrivia of the syntax that contains the XML doc comments
  2. Construct a Compilation, find the Symbol that has the XML doc comment and use the GetDocumentationComment() method on it.

完整的示例:

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);
    }
}

这篇关于如何使用Roslyn阅读XML文档注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆