Escape a string for xml use in C#
Posted in C#, Open Sitemap Generator on February 1st, 2007 @ 23:03 No Comments »
| Character | Escape Code | ||||
|---|---|---|---|---|---|
| Ampersand | & | & | |||
| Single Quote | ‘ | ' | |||
| Double Quote | “ | " | |||
| Greater Than | > | > | |||
| Less Than | < | < | |||
To achieve this result you could use the SecurityElement.Escape(string str) C# function, but it has a problem.
If your string has some entities already escaped, it escapes them again.
It happens to us testing our sitemaps generator when it finds URLs on a page that are already escaped.
So we’ve developed this function that tests every & character before to escape it.
public string EscapeXmlString(string URL)
{
//Avoid errors if the string is already escaped for xml use
for (int i = 0; i < URL.Length-1; i++)
{
if (URL[i] == ‘&’)
{
switch (URL[i + 1])
{
case ‘a’:
if ((i + 5 < URL.Length) && (URL.Substring(i, 6) == “'”))
{
continue;
}
else
{
if ((i + 4 < URL.Length) && (URL.Substring(i, 5) == “&”))
{
continue;
}
else
{
//Escape it
URL = URL.Insert(i+1, “amp;”);
}
}
break;
case ‘q’:
if ((i + 5 < URL.Length) && (URL.Substring(i, 6) == “"”))
{
continue;
}
else
{
//Escape it
URL = URL.Insert(i+1, “amp;”);
}
break;
case ‘g’:
if ((i + 3 < URL.Length) && (URL.Substring(i, 4) == “>”))
{
continue;
}
else
{
//Escape it
URL = URL.Insert(i+1, “amp;”);
}
break;
case ‘l’:
if ((i + 3 < URL.Length) && (URL.Substring(i, 4) == “<”))
{
continue;
}
else
{
//Escape it
URL = URL.Insert(i+1, “amp;”);
}
break;
default://Escape it
URL = URL.Insert(i+1, “amp;”);
break;
}
}
}
URL = URL.Replace(“‘”, “'”);
URL = URL.Replace(“\”“, “"”);
URL = URL.Replace(“>”, “>”);
URL = URL.Replace(“<”, “<”);
return URL;
}
Mike