using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; // Load the C# code file into a syntax tree var code = "int a = 1; var b = 2; float c = 3.0f;"; var tree = CSharpSyntaxTree.ParseText(code); // Get all the variable declaration syntax nodes var variableDeclarations = tree.GetRoot() .DescendantNodes() .OfType() .ToList(); // Print out the names of the variables and their types foreach (var variableDeclaration in variableDeclarations) { var variableType = variableDeclaration.Type.ToString(); foreach (var variable in variableDeclaration.Variables) { var variableName = variable.Identifier.ToString(); Console.WriteLine($"{variableType} {variableName}"); } }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; // Load the C# code file into a syntax tree var code = @"var message = ""Hello, world!"";"; var tree = CSharpSyntaxTree.ParseText(code); // Rename all the string literals with a new message var root = tree.GetRoot(); var stringLiterals = root.DescendantNodes().OfTypeThis example demonstrates how to use the Ancestors property to traverse from a literal expression node up to the root node of the syntax tree. The package library is Microsoft.CodeAnalysis.CSharp.() .Where(s => s.IsKind(SyntaxKind.StringLiteralExpression)); foreach (var stringLiteral in stringLiterals) { var newStringLiteral = SyntaxFactory.LiteralExpression( SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal("Goodbye, world!")); var newRoot = root.ReplaceNode(stringLiteral, newStringLiteral); root = newRoot; } // Print out the modified code Console.WriteLine(root.ToFullString());