Nisar Afridi Nisar Afridi - 1 month ago 15
C# Question

Replacing Special Character with their codes

I am passing XML data to a server from a text Box, now issue is XML is giving issues with symbols like & < |. So i want to replace these symbols with their equivalent codes.

if i use string.replace function it will replace the characters recently replaced as well.

.Replace("&", "&#38;")
.Replace("<", "&#60;")
.Replace("|", "&#124;")
.Replace("!", "&#33;")
.Replace("#", "&#35;")


As it go through complete string again and again.
So &<# will become "
&&#35;38;&&#35;60;
"

I also tried Dictionary method:

var replacements = new Dictionary<string, string>
{
{"&", "&#38;"},
{"<", "&#60;"},
{"|", "&#124;"},
{"!", "&#33;"},
{"#", "&#35;"}
}
var output = replacements.Aggregate(input, (current, replacement) => current.Replace(replacement.Key, replacement.Value));
return output;


But same issue here as well. I also tried string builder method, but same repeating replacement issue. Any Advise?

Answer
public static string Transform(string input, Dictionary<string, string> replacements)
    {
        string finalString = string.Empty;
        for (int i = 0; i < input.Length; i++)
        {
            if (replacements.ContainsKey(input[i].ToString()))
            {
                finalString = finalString + replacements[input[i].ToString()];
            }
            else
            {
                finalString = finalString + input[i].ToString();
            }
        }

        return finalString;
    }
Comments