private async Task<Document> FormatXmlAsync(Document document, LiteralExpressionSyntax sleSyntax, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken); var tree = root.SyntaxTree; //Get the character position of the LiteralExpressionSyntax FileLinePositionSpan position = tree.GetLineSpan(sleSyntax.Span); int cSpace = position.StartLinePosition.Character; //Figure out the preceeding trivia since we can't get the column position from GetLineSpan var parentTrivia = sleSyntax.GetLeadingTrivia().ToFullString(); var xml = sleSyntax.GetFirstToken().ValueText; var newXmlText = FormatXml(xml); //Process each line of the formatted XML and prepend the parent trivia & spaces string[] xmlLines = newXmlText.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None); for (int i = 1; i < xmlLines.Length; i++) { xmlLines[i] = parentTrivia + new String(' ', (cSpace + 2)) + xmlLines[i]; } newXmlText = String.Join("\r\n", xmlLines); var newXmlValue = "@\"" + newXmlText + "\""; var newNode = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.StringLiteralToken, newXmlValue, newXmlText, SyntaxTriviaList.Empty)); var newRoot = root.ReplaceNode(sleSyntax, newNode); return document.WithSyntaxRoot(newRoot); }
private async Task <Document> FormatXmlAsync(Document document, LiteralExpressionSyntax sleSyntax, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken); var tree = root.SyntaxTree; //Get the character position of the LiteralExpressionSyntax FileLinePositionSpan position = tree.GetLineSpan(sleSyntax.Span); int cSpace = position.StartLinePosition.Character; //Figure out the preceeding trivia since we can't get the column position from GetLineSpan var parentTrivia = sleSyntax.GetLeadingTrivia().ToFullString(); var xml = sleSyntax.GetFirstToken().ValueText; var newXmlText = FormatXml(xml); //Process each line of the formatted XML and prepend the parent trivia & spaces string[] xmlLines = newXmlText.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None); for (int i = 1; i < xmlLines.Length; i++) { xmlLines[i] = parentTrivia + new String(' ', (cSpace + 2)) + xmlLines[i]; } newXmlText = String.Join("\r\n", xmlLines); var newXmlValue = "@\"" + newXmlText + "\""; var newNode = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.StringLiteralToken, newXmlValue, newXmlText, SyntaxTriviaList.Empty)); var newRoot = root.ReplaceNode(sleSyntax, newNode); return(document.WithSyntaxRoot(newRoot)); }