简体   繁体   中英

Remove all SyntaxTrivia nodes from Roslyn SyntaxTree

I am trying to remove all nodes of type SyntaxTrivia from a SyntaxTree using Roslyn.

I tried to use the SyntaxRewriter class, but that does not work as SyntaxTrivia is non-nullable:

public class WhitespaceRemover : CSharpSyntaxRewriter
{
   public override SyntaxTrivia VisitTrivia(SyntaxTrivia trivia)
   {
       // Cannot convert null to 'SyntaxTrivia' because it is a non-nullable value type
       return null;
   }
}

What's the correct way to accomplish this?

I suppose that you need to rewrite a SyntaxNode invoking Microsoft.CodeAnalysis.SyntaxNodeExtensions.WithoutTrivia(...) , which will removes all trivias, instead of try to rewrite a SyntaxtTrivia .

Upd. @Emiswelt correctly mentioned that should override Visit method and additionally overriding VisitTrivia in the comment, which allows to remove non atached trivias from SyntaxTree

You can use it inside your syntax rewrite and it will looks like this:

public class WhitespaceRemover : CSharpSyntaxRewriter
{
    public override SyntaxNode Visit(SyntaxNode node) => base.Visit(node).WithoutTrivia();

    public override SyntaxTrivia VisitTrivia(SyntaxTrivia trivia) => default;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM