using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; ... SyntaxTree tree = CSharpSyntaxTree.ParseText("string foo = \"Hello\" + \" World\";"); var root = tree.GetRoot(); var stringLiterals = root.DescendantNodes().OfType() .Where(literal => literal.Kind() == SyntaxKind.StringLiteralExpression) .ToList();
using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; ... SyntaxTree tree = CSharpSyntaxTree.ParseText("int a = 5; int b = 7; int c = a + b;"); var root = tree.GetRoot(); var variables = root.DescendantNodes().OfTypeIn this example, we are using the DescendantNodes method to find all the descendant nodes of the root node of our syntax tree, this time only including nodes of the IdentifierNameSyntax type. We then go through each variable in our list and use the GetSymbolInfo method to get the symbol of the variable, which we use to then get the constant value of the variable. If the variable has a constant value, we replace the variable with a LiteralExpressionSyntax node containing the constant value.() .Where(variable => variable.Kind() == SyntaxKind.IdentifierName) .ToList(); foreach (var variable in variables) { var symbol = model.GetSymbolInfo(variable).Symbol; var value = model.GetConstantValue(variable); if (value.HasValue) { var literal = SyntaxFactory.LiteralExpression( SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal((int)value.Value)); root = root.ReplaceNode(variable, literal); } }